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!");
   };
);
0

2 Answers 2

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.)

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.