Glossary / Web Workers
Web Workers
Web Workers run JavaScript in a separate browser agent/thread so CPU-intensive work can proceed without blocking the main thread’s input and rendering. A worker has its own global context and event loop; it cannot directly manipulate the document DOM. Main thread and worker communicate through message APIs, normally using structured cloning or transfer of supported objects.
Lifecycle and messaging
const worker = new Worker(new URL("./compute-worker.js", import.meta.url), { type: "module" });
worker.postMessage({ task: "index", records });
worker.addEventListener("message", ({ data }) => render(data));
worker.addEventListener("error", reportWorkerError);
Workers can import scripts/modules and use many web APIs, but have different global objects and restrictions. postMessage usually clones data, which can be expensive for huge graphs; transfer an ArrayBuffer when ownership can move, or use SharedArrayBuffer with synchronization where required. Terminate workers when ownership ends, or implement graceful shutdown. Worker startup, message serialization, and context-switching have costs, so batch work and measure.
Workers are best for CPU-heavy tasks such as parsing, image processing, or indexing—not routine network I/O that browsers already handle asynchronously. They do not automatically improve total performance; they prevent main-thread blocking at the cost of memory and communication overhead. Keep UI DOM updates on the main thread and send minimal results back.
Interview questions
- Can a dedicated worker access document? No, it cannot manipulate the page DOM directly.
- How communicate? postMessage/message events, with clone/transfer semantics.
- When are workers useful? CPU-bound work that would block UI responsiveness.
- What costs matter? Startup, memory, data transfer/clone, and synchronization.