Skip to content

WebWorker、SharedWorker 和 ServiceWorker 有哪些区别?

Posted on:2024年8月14日 at 23:23

WebWorkerSharedWorkerServiceWorker 都是 Web API 提供的用于在后台线程执行 JavaScript 代码的机制,但它们有不同的用途和特性。下面是它们的主要区别:

1. WebWorker

示例

// main.js
const worker = new Worker("worker.js");
worker.postMessage("Hello, worker!");
worker.onmessage = (event) => console.log(event.data);

// worker.js
self.onmessage = (event) => {
  self.postMessage(`Received: ${event.data}`);
};

2. SharedWorker

示例

// main1.js
const worker = new SharedWorker("shared-worker.js");
worker.port.postMessage("Hello from page 1!");
worker.port.onmessage = (event) => console.log(event.data);

// main2.js
const worker = new SharedWorker("shared-worker.js");
worker.port.postMessage("Hello from page 2!");
worker.port.onmessage = (event) => console.log(event.data);

// shared-worker.js
self.onconnect = (event) => {
  const port = event.ports[0];
  port.onmessage = (event) => {
    port.postMessage(`Received: ${event.data}`);
  };
};

3. ServiceWorker

示例

// service-worker.js
self.addEventListener("install", (event) => {
  // Perform install steps
  event.waitUntil(
    caches.open("my-cache").then((cache) => {
      return cache.addAll(["/", "/styles/main.css", "/script/main.js"]);
    }),
  );
});

self.addEventListener("fetch", (event) => {
  event.respondWith(
    caches.match(event.request).then((response) => {
      return response || fetch(event.request);
    }),
  );
});
原文转自:https://fe.ecool.fun/topic/f18218c8-4c74-4631-b66d-e7ac65929f35