第三方库
workerize
let worker = workerize(`
export function add(a, b) {
// block for half a second to demonstrate asynchronicity
let start = Date.now();
while (Date.now()-start < 500);
return a + b;
}
`);
(async () => {
console.log("3 + 9 = ", await worker.add(3, 9));
console.log("1 + 2 = ", await worker.add(1, 2));
})();
我们也可以使用 workerize-loader 作为
// worker.js
export function expensive(time) {}
// app.js
import worker from "workerize-loader!./worker";
let instance = worker(); // `new` is optional
instance.expensive(1000).then(count => {
console.log(`Ran ${count} loops`);
});
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().
Comlink
通过提供
Simple App
- main.js
import * as Comlink from "https://unpkg.com/comlink/dist/esm/comlink.mjs";
async function init() {
const worker = new Worker("worker.js");
// WebWorkers use `postMessage` and therefore work with Comlink.
const obj = Comlink.wrap(worker);
alert(`Counter: ${await obj.counter}`);
await obj.inc();
alert(`Counter: ${await obj.counter}`);
}
init();
- worker.js
importScripts("https://unpkg.com/comlink/dist/umd/comlink.js");
// importScripts("../../../dist/umd/comlink.js");
const obj = {
counter: 0,
inc() {
this.counter++;
}
};
Comlink.expose(obj);
Callback
- main.js
import * as Comlink from "https://unpkg.com/comlink/dist/esm/comlink.mjs";
// import * as Comlink from "../../../dist/esm/comlink.mjs";
function callback(value) {
alert(`Result: ${value}`);
}
async function init() {
const remoteFunction = Comlink.wrap(new Worker("worker.js"));
await remoteFunction(Comlink.proxy(callback));
}
init();
- worker.js
importScripts("https://unpkg.com/comlink/dist/umd/comlink.js");
// importScripts("../../../dist/umd/comlink.js");
async function remoteFunction(cb) {
await cb("A string from a worker");
}
Comlink.expose(remoteFunction);