As of now, my current project involves the task of transitioning an existing web application to require.js
. Most aspects of the process are proceeding smoothly, except for the functionality that utilizes web-workers. One such example is a worker defined in a separate JavaScript file named MeshLoader.js
, responsible for loading a 3D model from an STL file:
importScripts('../lib/three.min.js', '../lib/STLLoader.js');
onmessage = function(e) {
var blob = e.data;
var reader = new FileReaderSync();
readContents(reader.readAsArrayBuffer(blob));
};
function readContents(contents) {
try {
var geometry = new THREE.STLLoader().parse(contents);
} catch (e) {
// error handling
}
var attributes = {};
// further parsing of the file takes place here
// ...
postMessage({
status: 'completed',
attributes: attributes,
});
}
A minor note: The STLLoader.js
module serves as a plugin within three.js
, defining the STLLoader
object and incorporating it into the THREE
namespace. Here's how I refactored it using require.js
:
importScripts('../lib/require.min.js');
require({
baseUrl: '../lib'
}, [
'require', 'three.min', 'stlloader'
],
function(require, THREE, STLLoader) {
onmessage = function(e) {
var blob = e.data;
var reader = new FileReaderSync();
readContents(reader.readAsArrayBuffer(blob));
};
function readContents(contents) {
try {
var geometry = new THREE.STLLoader().parse(contents);
} catch (e) {
// error handling
}
var attributes = {};
// same code as in the initial version
// ...
postMessage({
status: 'completed',
attributes: attributes,
});
}
return onmessage;
});
The worker is invoked in the following manner:
var worker = new Worker('js/workers/MeshLoader.js');
worker.postMessage(blob);
worker.onmessage = function (event) {
if (event.data.status == 'completed') {
// ...
} else if (event.data.status == 'failed') {
// ...
} else if (event.data.status == 'working') {
// ...
}
};
However, it seems that the worker is not being called at all. Could it be necessary to declare it as a module in the requirejs.config()
section and then incorporate the module as a dependency in other modules that utilize this worker?