Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

As far as I can tell, web workers need to be written in a separate JavaScript file, and called like this:

(据我所知,网络工作者需要用一个单独的JavaScript文件编写,并按如下方式调用:)

new Worker('longrunning.js')

I'm using the closure compiler to combine and minify all my JavaScript source code, and I'd rather not have to have my workers in separate files for distribution.

(我正在使用闭包编译器来合并和最小化我的所有JavaScript源代码,而我不必将我的工作人员放在单独的文件中进行分发。)

Is there some way to do this?

(有什么办法可以做到这一点?)

new Worker(function() {
    //Long-running work here
});

Given that first-class functions are so crucial to JavaScript, why does the standard way to do background work have to load a whole other JavaScript file from the web server?

(鉴于一流的功能对JavaScript至关重要,为什么进行后台工作的标准方法必须从Web服务器加载整个其他JavaScript文件?)

  ask by Ben Dilts translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
154 views
Welcome To Ask or Share your Answers For Others

1 Answer

http://www.html5rocks.com/en/tutorials/workers/basics/#toc-inlineworkers

(http://www.html5rocks.com/zh-CN/tutorials/workers/basics/#toc-inlineworkers)

What if you want to create your worker script on the fly, or create a self-contained page without having to create separate worker files?

(如果您想即时创建工作脚本或创建独立页面而不需要创建单独的工作文件怎么办?)

With Blob(), you can "inline" your worker in the same HTML file as your main logic by creating a URL handle to the worker code as a string

(使用Blob(),您可以通过将工作程序代码的URL句柄创建为字符串,从而在与主逻辑相同的HTML文件中“内联”您的工作程序)


Full example of BLOB inline worker:(BLOB内联工作程序的完整示例:)

 <!DOCTYPE html> <script id="worker1" type="javascript/worker"> // This script won't be parsed by JS engines because its type is javascript/worker. self.onmessage = function(e) { self.postMessage('msg from worker'); }; // Rest of your worker code goes here. </script> <script> var blob = new Blob([ document.querySelector('#worker1').textContent ], { type: "text/javascript" }) // Note: window.webkitURL.createObjectURL() in Chrome 10+. var worker = new Worker(window.URL.createObjectURL(blob)); worker.onmessage = function(e) { console.log("Received: " + e.data); } worker.postMessage("hello"); // Start the worker. </script> 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...