Search code examples
javascriptthree.jsweb-worker

Web workers for loading object in three.js


I'd like to load and parse a 3D file using three.js and the corresponding Loader (e.g. PLYLoader). However, because my 3D files are very large, the Loader spends a long time parsing the file and locks up all JS-based UI on the page. I was wondering what the best way to load the file would be without locking the UI.

I imagine the solution is based on web workers. However, I'm not sure about what the best way to approach it is. The Loaders require the main three.js file, which in turn performs DOM manipulations. Therefore, I cannot naively just copy the Loader functionality into its own web-worker file.

I found that a similar question was asked previously. However, the answer seems to be specifically directed in the case of textures, which appear to have differences in web-worker applicability.

Loading texture from Web Worker in Three.js


Solution

  • You actually can include the loading functionality into a web worker. Just import three.js and the respective loader file:

    myWorker.js
    ...
    importScripts('/path/to/js/three.js', '/path/to/js/threeXYZLoader.js');
    

    After that you can load your object just as described in the Three.js example. The trickier part is to get your loaded object back into your main thread in order to be rendered. Have a look at this approach using Worker.postMessage and Transferable object as a starting point.