I have a JavaScript module like so:
function difference(a, b){
return a - b;
}
export {difference};
This works fine when importing it into my main script.
import * as MathUtils from './math-utils.js';
However, I want to also import it into a Web Worker. The only cross-browser way to do this seems to be the following:
self.importScripts('/scripts/math-utils.js');
I obviously get an error when doing this because of the export statement at the end of the module. Is there any way to import the same script into a Web Worker that is cross-browser? Or at least to pass the functions to the Web Worker from the main script?
Thanks in advance!
Update:
I came up with this polyfill, which needs to be called from within the onmessage function of the Worker. However, this is not a very elegant solution and I would appreciate it, if anyone knew of a better way.
function importScript(path){
return new Promise((resolve, reject) => {
fetch(path).then((response) => {
if(response.status == 200){
return response.text();
}
}).then((script) => {
if(typeof(script) == 'undefined'){
// Import failed
reject();
}
else{
// Remove export statement from script
script = script.replace(/export(.*);/m, '');
// Create blob
var blob = new Blob([script], {type : 'text/javascript'});
var url = URL.createObjectURL(blob);
self.importScripts(url);
resolve();
}
});
});
}
Edit: This is not a duplicate of Web Workers - How To Import Modules!
The accepted answers on that question only accounts for Chromium-based browsers, I am looking for a cross-browser solution.