HTML5 web worker简介
HTML5 web worker就像在java中新建一个thread一样,创建一个独立的环境运行计算量比较大的程序,于目前来说还是没有太大的用武之地,但是估计以后可能用途比较大。
基本的代码很简单:
[html]
var worker = new Worker('doWork.js');
worker.addEventListener('message', function(e) {
console.log('Worker said: ', e.data);
}, false);
worker.postMessage('Hello World'); // Send data to our worker.
doWork.js
[html]
self.addEventListener('message', function(e) {
self.postMessage(e.data);
}, false);
要注意的是在页面里我们需要建立双向通讯机制:postMessage和 addEventListener (in page we need postMessage() to post it to worker and onmessage to receive from worker)
在worker.js中也要建立双向通讯机制 (in worker we also need postMessage to post it to page and on message to receive from page)
其他要注意的是error handling和如果你不想建立单独的worker.js也可以使用FileURL建立 (use objectURL to load worker in the same page)
[html]
// Prefixed in Webkit, Chrome 12, and FF6: window.WebKitBlobBuilder, window.MozBlobBuilder
var bb = new BlobBuilder();
bb.append("onmessage = function(e) { postMessage('msg from worker'); }");
// Obtain a blob URL reference to our worker 'file'.
// Note: window.webkitURL.createObjectURL() in Chrome 10+.
var blobURL = window.URL.createObjectURL(bb.getBlob());
作者:baoeni
补充:web前端 , HTML 5 ,