Worker

Web Worker

基础使用

1
// 判断浏览器是否支持 Worker
2
typeof Worker !== 'undefined';
3
4
// 从脚本中创建 Worker
5
new Worker('workers.js');
6
7
// 使用字符串方式创建 Worker
8
new Worker('data:text/javascript;charset=US-ASCII,...');
Copied!

worker-loader

worker-loader 是一个 webpack 插件,可以将一个普通 JS 文件的全部依赖提取后打包并替换调用处,以 Blob 形式内联在源码中。
1
import Worker from 'worker-loader!./file.worker.js';
2
3
const worker = new Worker();
4
5
// 转化为下述代码
6
const blob = new Blob([codeFromFileWorker], { type: 'application/javascript' });
7
const worker = new Worker(URL.createObjectURL(blob));
Copied!

Blob

我们也可以自己通过 Blob 的方式创建:
1
const code = `
2
importScripts('https://xxx.com/xxx.js');
3
self.onmessage = e => {};
4
`;
5
6
const blob = new Blob([code], { type: 'application/javascript' });
7
const worker = new Worker(URL.createObjectURL(blob));
Copied!

workerize/workerize-loader

1
let worker = workerize(`
2
export function add(a, b) {
3
// block for half a second to demonstrate asynchronicity
4
let start = Date.now();
5
while (Date.now()-start < 500);
6
return a + b;
7
}
8
`);
9
10
(async () => {
11
console.log('3 + 9 = ', await worker.add(3, 9));
12
console.log('1 + 2 = ', await worker.add(1, 2));
13
})();
Copied!
我们也可以使用 workerize-loader 作为 Webpack 插件来加载 Web Worker:
1
// worker.js
2
export function expensive(time) {}
3
4
// app.js
5
import worker from 'workerize-loader!./worker';
6
7
let instance = worker(); // `new` is optional
8
9
instance.expensive(1000).then(count => {
10
console.log(`Ran ${count} loops`);
11
});
Copied!
You cannot use Local Storage in service workers. It was decided that service workers should not have access to any synchronous APIs. You can use IndexedDB instead, or communicate with the controlled page using postMessage().

网络请求

By default, cookies are not included with fetch requests, but you can include them as follows: fetch(url, {credentials: 'include'}).
1
function XHRWorker(url, ready, scope) {
2
var oReq = new XMLHttpRequest();
3
oReq.addEventListener(
4
'load',
5
function() {
6
var worker = new Worker(
7
window.URL.createObjectURL(new Blob([this.responseText]))
8
);
9
if (ready) {
10
ready.call(scope, worker);
11
}
12
},
13
oReq
14
);
15
oReq.open('get', url, true);
16
oReq.send();
17
}
18
19
function WorkerStart() {
20
XHRWorker(
21
'http://static.xxx.com/js/worker.js',
22
function(worker) {
23
worker.postMessage('hello world');
24
worker.onmessage = function(e) {
25
console.log(e.data);
26
};
27
},
28
this
29
);
30
}
31
32
WorkerStart();
Copied!
Last modified 2yr ago