2

I'm developing a project with multithreading. For this I spawn 8 web workers, all with the same source code. These are spawned as follows:

  var workers = [];

  for (var i = 0; i < 8; i++) {
    workers.push(new Worker('worker.js'));
  }

But this requires the worker.js file to be downloaded 8 times. Is there any way I can require the source file just once, and then re-use it?

Bonus question: is there any way to do this for importScripts in the workers. Cause every worker is importing the same script now.

Thomas Wagenaar
  • 6,489
  • 5
  • 30
  • 73
  • AFAIK, if it's the same file browser won't download it again. It uses the first downloaded one. I think no point of re downloading here.. – Jyothi Babu Araja Sep 08 '17 at 11:24
  • 1
    Are you sure the file is downloaded each time instead of retrieved from the cache? I'm encountering questions with how to deal with cached worker files, like: [Web Worker: How to prevent that file gets loaded from cache?](https://stackoverflow.com/questions/33356430/web-worker-how-to-prevent-that-file-gets-loaded-from-cache) – yuriy636 Sep 08 '17 at 11:28

1 Answers1

0

I suggest that you use code that is normally used to create worker from string, here: https://stackoverflow.com/a/33432215/607407

This way you can load the string source in the main thread and then have workers execute it. Workers must parse their source, since functions in javascript cannot be cloned (think of all the implications given by scope inheritance).

Workers can be given this source as well, using string. This way you can spawn indefinite number of workers using the same sourcecode.

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778