概括
blob:
适用于 Chrome 8+、Firefox 6+、Safari 6.0+、Opera 15+
data:application/javascript
歌剧 10.60 - 12
eval
否则(IE 10+)
URL.createObjectURL(<Blob blob>)
可用于从字符串创建 Web 工作者。可以使用已弃用BlobBuilder
的API或构造函数来创建 blob 。Blob
演示:http: //jsfiddle.net/uqcFM/49/
// URL.createObjectURL
window.URL = window.URL || window.webkitURL;
// "Server response", used in all examples
var response = "self.onmessage=function(e){postMessage('Worker: '+e.data);}";
var blob;
try {
blob = new Blob([response], {type: 'application/javascript'});
} catch (e) { // Backwards-compatibility
window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
blob = new BlobBuilder();
blob.append(response);
blob = blob.getBlob();
}
var worker = new Worker(URL.createObjectURL(blob));
// Test, used in all examples:
worker.onmessage = function(e) {
alert('Response: ' + e.data);
};
worker.postMessage('Test');
兼容性
以下浏览器源代码支持 Web Worker :
- 铬 3
- 火狐 3.5
- IE 10
- 歌剧 10.60
- 野生动物园 4
这个方法的支持是基于Blob
API和URL.createObjectUrl
方法的支持。Blob
兼容性:
- Chrome 8+ (
WebKitBlobBuilder
), 20+ (Blob
构造函数)
- Firefox 6+ (
MozBlobBuilder
), 13+ (Blob
构造函数)
- Safari 6+(
Blob
构造函数)
IE10 支持MSBlobBuilder
和URL.createObjectURL
. 但是,尝试从blob:
-URL 创建 Web Worker 会引发 SecurityError。
Opera 12 不支持URL
API。URL
由于. _ _browser.js
后备 1:数据 URI
Opera 支持 data-URIs 作为Worker
构造函数的参数。注意:不要忘记转义特殊字符(例如#
和%
)。
// response as defined in the first example
var worker = new Worker('data:application/javascript,' +
encodeURIComponent(response) );
// ... Test as defined in the first example
演示:http: //jsfiddle.net/uqcFM/37/
后备 2:评估
eval
可用作 Safari (<6) 和 IE 10 的后备。
// Worker-helper.js
self.onmessage = function(e) {
self.onmessage = null; // Clean-up
eval(e.data);
};
// Usage:
var worker = new Worker('Worker-helper.js');
// `response` as defined in the first example
worker.postMessage(response);
// .. Test as defined in the first example