Web Workers
A web worker is a browser thread that runs a script without access to the DOM. You talk to it with messages; heavy CPU work can stay off the page's event loop.
Detailed Explanation
The page (the window agent) has one thread for JavaScript and rendering. A long Fibonacci or a large parse blocks clicks and paint. A worker is a second agent: its own event loop, its own heap, no document, no window. You create it with new Worker(url) or new Worker(url, { type: "module" }).
Communication is postMessage(data) and message events. Structured clone copies the data. Functions, DOM nodes, and class identity do not survive. ArrayBuffer can be transferred (postMessage(buf, [buf])) so the sender loses access and the copy is a move. SharedArrayBuffer plus Atomics is the shared-memory path, gated by cross-origin isolation.
Workers can use fetch, IndexedDB, WebSocket, timers, and importScripts / import. They cannot touch the DOM. To update the UI, send a message back and let the page write the DOM.
Kinds: dedicated workers (one page), shared workers (several tabs of the same origin, SharedWorker), service workers (a different job: network proxy and cache; not a compute thread you postMessage a sort to). Worker from a worker is allowed (nested workers) in some engines.
Errors arrive as error events on the Worker object. worker.terminate() stops the thread immediately. The worker can call self.close().
What it costs you: latency and complexity. Creating a worker and cloning 10 MB of JSON has a cost; for 2 ms of work you lost. Debugging is a second context. Bundlers must emit a separate worker file or use URL + import.meta.url. Shared state is gone; you design messages.
Reach for a worker when a task is tens of milliseconds or more of CPU, or when you parse large data. Reach for requestIdleCallback or chunked await for lighter yields. Reach for a service worker for offline and caching, not for math.
Code Examples
main.js (browser)
// main.js (browser)
const worker = new Worker(new URL("./hash-worker.js", import.meta.url), {
type: "module",
});
worker.addEventListener("message", (event) => {
console.log(event.data);
});
worker.postMessage({ text: "hello" });hash-worker.js
// hash-worker.js
self.addEventListener("message", (event) => {
const text = event.data.text;
let h = 0;
for (let i = 0; i < text.length; i += 1) {
h = (h + text.charCodeAt(i)) | 0;
}
self.postMessage({ hash: h });
});const buffer = new ArrayBuffer(8);
worker.postMessage(buffer, [buffer]);
console.log(buffer.byteLength); // => 0 (transferred)Common Gotchas
Workers cannot access the DOM
`document` is undefined. Send results back to the page.
`postMessage` clones
large graphs are expensive; transfer `ArrayBuffer`s or send ids.
Functions and prototypes do not clone
send plain data, rebuild classes on the other side.
Service workers are not compute workers
they intercept fetch and manage caches. Wrong tool for a sort.