Reputation: 6844
I have multiple inline workers that I need to run. My problem is that every instance needs to share the same scripts that are imported. But on every instance that I created, it redownloads the scripts.
function workerFn(){
importScripts('https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js');
// Each time this function will do something else
postMessage(_.head([1,2,3]));
}
var code = workerFn.toString();
code = code.substring(code.indexOf("{") + 1, code.lastIndexOf("}"));
var blob = new Blob([code], {type: "application/javascript"});
var worker = new Worker(URL.createObjectURL(blob));
var worker2 = new Worker(URL.createObjectURL(blob));
worker.onmessage = function (m) {};
worker2.onmessage = function (m) {};
So, in the above example, lodash
will download twice. How can I prevent this?
Upvotes: 3
Views: 1668
Reputation: 53129
Unfortunately, you cannot. It's up to the browser whether it downloads the scripts or not. I assume this does not even happen in every browser.
The only way to avoid browser re-downloading the script would be to either a) have it compiled in your code (eg. web pack) or b) download it via AJAX, assuming CDN allows requests from other domains.
Neither of these thing is something I would recommend for production code.
Upvotes: 1