Glossary / Shared Workers
Shared Workers
A SharedWorker is a worker that can be connected to by multiple same-origin browsing contexts, such as tabs or frames, subject to browser and security-context rules. It can centralize coordination, caching, or a connection across clients. Unlike a dedicated worker’s single owner relationship, communication uses a MessagePort associated with each connecting document.
Connection and lifecycle
const worker = new SharedWorker("shared.js", { name: "session-coordinator" });
worker.port.start();
worker.port.postMessage({ type: "subscribe" });
worker.port.onmessage = ({ data }) => handle(data);
The worker’s connect event exposes ports for clients. Define per-port protocol, authentication/authorization assumptions, error handling, and cleanup when clients disconnect. A shared worker’s lifetime is controlled by connected contexts and browser policy; do not use it as durable storage or assume it survives navigation, browser shutdown, or process changes.
Support varies more than dedicated workers, particularly across browser/platform contexts. Feature-detect and provide a fallback. Shared state inside the worker still needs consistency rules, though its JavaScript agent runs one job at a time; shared ArrayBuffer usage can introduce true cross-agent memory concurrency.
Interview questions
- Dedicated versus shared worker? Dedicated worker belongs to one creator; SharedWorker can be connected to by multiple contexts.
- What channel does a SharedWorker use? MessagePort for each connection.
- Is it persistent across browser restarts? No.
- What is a common use? Cross-tab coordination or a shared connection/cache when support and lifecycle fit.