Loading vtk.js dynamically

I’m trying to use vtk.js in a jupyter notebook with mixed success. When it works, it works great:


But I’m struggling a lot with dynamically loading vtk.js. Most often it does not work (it does work sometimes - which makes me even more confused). I tried this:

new Promise(function(resolve, reject) {
	var script = document.createElement("script");
	script.onload = resolve;
	script.onerror = reject;
	script.src = "https://unpkg.com/vtk.js@14.16.4/dist/vtk.js";
	document.head.appendChild(script);
}).then(() => {
console.log(vtk)
});

and this

require.config({
        "paths": {"vtk": "https://unpkg.com/vtk"},
        "exports": {"vtk": null},
        "shim": {
            "vtk": {"exports": "vtk"},
        }
    }
);

require(["vtk"], function(vtk) {console.log(vtk);});

To sum up, the question is: what would be the conanical way of loading vtk.js?

Thanks,
Adam

Do you have a typo on your second approach? Should it be vtk.js rather than vtk?

The first one should work except if Jupyter is using some iframe and therefore reduce the scope of that script loading to some extent.

I don’t know enough about Jupyter to comment on that though.

requirejs does add .js on its own, so there is no typo in the location. Is there anything special about vtk.js that could cause such intermittent failures? I tested both approaches with e.g. d3.js and they seem to always work.

Nothing that I think of. I’m wondering if you import twice what happen? Maybe that is the issue? Hard to tell.

Thanks for the help. I guess it is something jupyter specific - I asked the question here: Trying to load vtk.js dynamically - Notebook - Jupyter Community Forum .

This seems to work. I’d really would like to understand why…

new Promise(function(resolve, reject) {
        require.config({
        "paths": {"vtk": "https://unpkg.com/vtk"},
    }
);
    require(["vtk"], resolve);
}).then(() => {
    console.log(vtk);
    console.log("Loaded vtk.js library");
});

It looks like the require.config add the script tag. The require([vtk]..) wait for the script to be downloaded and interpreted.

Yes it does. I used this approach without wrapping it in a promise (see the original post) and it did not always work.

It also does not really explain why the promise+adding a script element by hand did not work.

Hum indeed, that is intriguing… I’m not sure why, but it is nice to see it work now and have a path forward.

Yes, thanks for your help! If anyone is interested the PR is here: Implement importBrep and vtkPolyData export by adam-urbanczyk · Pull Request #735 · CadQuery/cadquery · GitHub