3

In order to instantiate a new Worker, the logic is the following:

var w = new Worker("demo_workers.js");

demo_workers.js contains the definition of what the worker will do. Is it possible to avoid the creation of a new .js and pass an internal function to that constructor? Something like

var w = new Worker(
   function(){
       alert("hey!");
   };
);
Tareq Salah
  • 3,720
  • 4
  • 34
  • 48
TheUnexpected
  • 3,077
  • 6
  • 32
  • 62

2 Answers2

2

You can't create a worker using a function, since this would cause a lot of concurrency problems. You need to pass a URL to a script.

However, you can use a URL for a Blob which you created at run-time. MDN has a great example where they create a worker using the contents of a non-evaluated <script> tag on the same page. This way, you can place the worker script on the same HTML page as the code using the worker, thus saving a HTTP request for the worker script. (Of course, if the worker script is static, it's probably better to keep it in a separate file which can be cached by the browser.)

Mattias Buelens
  • 19,609
  • 4
  • 45
  • 51
1

No the specification states that you must reference a javascript source.

http://www.w3.org/TR/workers/#worker

"Worker(scriptURL)" is the only option specified.

Ted Johnson
  • 4,315
  • 3
  • 29
  • 31
  • Also: http://stackoverflow.com/questions/5408406/web-workers-without-a-separate-javascript-file – Ted Johnson Dec 25 '13 at 10:59
  • Mattias points out something that is possible but might not be a good practice which he points out. Either way both are urls which is what the specification. – Ted Johnson Dec 25 '13 at 11:57