Reference
One process, many same-origin contexts. Normative: WHATWG Web workers.
const worker = new SharedWorker("shared.js");
// optional name to distinguish instances:
// new SharedWorker("shared.js", "session-bus");
// Communicate via explicit port (not worker.onmessage)
worker.port.onmessage = (e) => { /* … */ };
worker.port.postMessage({ type: "hello" });
// If using addEventListener for "message", call start():
// worker.port.start();
// SharedWorkerGlobalScope
onconnect = (e) => {
const port = e.ports[0];
port.onmessage = (ev) => {
// handle; reply on this port only, or fan-out to all ports you stored
port.postMessage({ type: "ack", echo: ev.data });
};
// port.start() if you used addEventListener instead of onmessage
};
extendedLifetime for cleanup (MDN lifetime notes).
| Need | Prefer |
|---|---|
| Offload CPU for one page | Dedicated Worker |
| Pub/sub between tabs only | BroadcastChannel (lighter; no shared process) |
| One shared in-memory coordinator | SharedWorker (ports + fan-out you implement) |
| Offline / network proxy | Service Worker |
chrome://inspect/#workersabout:debugging#workers