質問

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!");
   };
);
役に立ちましたか?

解決 2

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.

他のヒント

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top