Web Workers: Offloading Work Off the Main Thread
The main thread does everything: layout, paint, your JavaScript, event handlers, React reconciliation. When a loop takes longer than about sixteen milliseconds β the frame budget at sixty hertz β the page stops responding. Buttons feel dead, scrolling stutters, and the browser's "page unresponsive" dialog gets closer. Web Workers solve this by giving you real threads: separate JavaScript environments with their own event loop, connected to the page only through message passing.
The trade is absolute isolation. A worker has no document, no window, no DOM nodes β not even an alert. Everything crossing the boundary is copied or transferred, and every hop costs. Used for the right jobs β parsing large files, crunching numbers, searching text, encoding media β workers transform janky pages into smooth ones. Used for trivial work, they add latency and complexity for nothing.
The Isolation Boundary
| Capability | Main thread | Worker |
|---|---|---|
| DOM access | Yes | No |
| window, document | Yes | Absent entirely |
| Timers and console | Yes | Yes |
| fetch, WebSocket, IndexedDB | Yes | Yes |
| importScripts or module imports | Yes | Yes |
| Shared memory via ArrayBuffer | Transferable | Transferable |
| Shared memory via Atomics | Yes | Yes, with SharedArrayBuffer |
The absence of the DOM is not a limitation to work around; it is the design. Because a worker cannot touch the page, the browser can run it on another core without synchronizing against layout at all.
Workers also inherit their own global scope. There is no window, but there are timers, the console, the fetch API, WebSocket, IndexedDB, cache storage, and β in module workers β static import statements that pull in other files. Structured patterns help: keep worker code free of page-specific assumptions, pass plain data across the boundary, and treat the worker like a small server process whose API happens to be postMessage.
Error handling deserves special attention because the isolation cuts both ways. An uncaught exception inside a worker does not bubble to the page's window.onerror; it arrives through the worker's onerror property on the main thread, and the worker keeps running. Attach that handler at creation time, decide explicitly whether to terminate and recreate the worker on fatal errors, and surface failures to the user instead of leaving a spinner that will spin forever. Debugging follows the same rules as any other script: workers get their own devtools context, listed under the Sources panel by their script URL, with real breakpoints and console output.
A Dedicated Worker Doing Real Work
A dedicated worker is created from a script file and serves one page. The classic use is image processing β downscaling an uploaded photo before upload:
// main.js
const input = document.getElementById('photo');
const status = document.getElementById('status');
const worker = new Worker('/workers/downscale.js', { type: 'module' });
worker.onmessage = (event) => {
const { blob, width, height } = event.data;
status.textContent = 'Resized to ' + width + 'Γ' + height;
preview.src = URL.createObjectURL(blob);
};
worker.onerror = (event) => {
status.textContent = 'Resize failed: ' + event.message;
};
input.addEventListener('change', async () => {
const file = input.files[0];
if (!file) return;
status.textContent = 'Resizingβ¦';
const bitmap = await createImageBitmap(file);
worker.postMessage(
{ bitmap, maxEdge: 1600 },
{ transfer: [bitmap] }
);
});
// /workers/downscale.js
self.onmessage = async (event) => {
const { bitmap, maxEdge } = event.data;
const scale = Math.min(1, maxEdge / Math.max(bitmap.width, bitmap.height));
const width = Math.round(bitmap.width * scale);
const height = Math.round(bitmap.height * scale);
const offscreen = new OffscreenCanvas(width, height);
const ctx = offscreen.getContext('2d');
ctx.drawImage(bitmap, 0, 0, width, height);
const blob = await offscreen.convertToBlob({ type: 'image/jpeg', quality: 0.85 });
self.postMessage({ blob, width, height });
};
The main thread's only jobs are reading the file, handing over a bitmap, and updating the UI. The resize itself β decode, scale, re-encode β runs entirely off the critical path, so the interface stays interactive even on a five-megabyte phone snapshot. OffscreenCanvas is what makes pixel work possible without a document: the same 2D context API, rendering into an invisible surface the worker owns.
Structured Clone and Transferables
Messages between threads are serialized with the structured clone algorithm: objects, arrays, Maps, Sets, Dates, and ArrayBuffers all survive the trip, but functions, DOM nodes, class instances with methods, and symbols do not. For a large binary payload, cloning means copying β and copying a fifty-megabyte buffer stalls both threads. The transfer option moves ownership instead:
// Sender
const buffer = new ArrayBuffer(1024 * 1024 * 50);
worker.postMessage({ buffer }, { transfer: [buffer] });
// buffer is now neutered; sender.byteLength is 0
// Receiver
self.onmessage = (event) => {
const { buffer } = event.data;
processBytes(buffer);
};
Transfer is one-way ownership, not a shared lock: after sending, the sender cannot touch the buffer at all. When both sides need the same data repeatedly, a SharedArrayBuffer plus Atomics gives true shared memory, subject to cross-origin isolation headers being configured on the server.
Designing the Message Protocol
Raw postMessage calls become unmanageable quickly. Give every message a type field, and match requests to responses with an id so concurrent work does not interleave:
// main.js
let nextId = 1;
const pending = new Map();
function callWorker(worker, type, payload, transfer = []) {
return new Promise((resolve, reject) => {
const id = nextId++;
pending.set(id, { resolve, reject });
worker.postMessage({ id, type, payload }, { transfer });
});
}
worker.onmessage = (event) => {
const { id, type, payload, error } = event.data;
const entry = pending.get(id);
if (!entry) return;
pending.delete(id);
if (error) entry.reject(new Error(error));
else entry.resolve(payload);
};
const result = await callWorker(worker, 'analyze', dataset);
The worker answers with the same id, and progress events reuse it with a distinct type so the caller can update a progress bar without confusing interim notifications for final results. Cancelation is worth designing in from the start: a cancel message that the worker checks between chunks lets a user abandon a long search without closing the tab.
SharedWorkers Across Tabs
A SharedWorker persists as long as any tab holds a port, which makes it the natural home for cross-tab coordination β a single WebSocket connection feeding every tab, or a cache that is filled once:
// client.js
const shared = new SharedWorker('/workers/hub.js', { type: 'module' });
shared.port.start();
shared.port.postMessage({ type: 'subscribe', channel: 'prices' });
shared.port.onmessage = (event) => renderPrice(event.data);
// /workers/hub.js
const ports = new Set();
self.onconnect = (event) => {
const port = event.ports[0];
ports.add(port);
port.onmessage = (message) => {
if (message.data.type === 'subscribe') {
// wire the port to a shared WebSocket and fan out updates
for (const other of ports) other.postMessage(message.data);
}
};
port.start();
};
Every port is an independent two-way pipe; the worker decides what to broadcast and what to keep per-connection. The failure mode to remember is leaked ports: if a page forgets to close its port on unload, the SharedWorker may never terminate even after the last visible tab is gone.
When a Worker Is Not Worth It
Worker startup costs tens of milliseconds, and every message pays serialization. Moving a five-line filter into a worker usually makes it slower and always makes it harder to debug. Good candidates share three traits: the computation runs longer than a frame budget, its inputs and outputs are mostly data rather than live references, and it is CPU-bound rather than waiting on the network. DOM measurement, reactive state updates, and event wiring belong on the main thread β pair the worker with a framework boundary instead, and keep the worker pure: input in, result out, no opinions about the page.
Build tooling makes the plumbing cheap enough that the decision is mostly about the data shape. Vite, webpack, and Next.js all support importing a worker file with a one-line syntax that handles bundling, hashing, and the correct URL at runtime. That removes the old excuse of hand-managing worker script paths β what remains is the design question of whether the work is heavy enough, and whether the round trip of serialization is smaller than the cost of doing the work inline. A useful heuristic from production codebases: if the task runs on every keystroke and takes more than a few milliseconds, it belongs in a worker; if it runs once per page view, the main thread will survive.
π‘Profile before you offload
The performance panel will tell you whether a function is actually blocking frames. A hundred-millisecond task that runs once at startup is a different problem from a two-hundred-millisecond task that runs on every keystroke; only the second usually justifies the worker plumbing.
Common Mistakes
Touching the DOM inside a worker and getting a ReferenceError
Fix: Pass data in, render on the main thread β workers have no document by design.
Cloning multi-megabyte buffers with structured clone
Fix: Use the transfer list to move ArrayBuffers and ImageBitmaps by ownership.
Fire-and-forget postMessage with no protocol
Fix: Tag messages with type and id fields and return responses that echo the id.
Offloading trivial work that finishes in under a frame
Fix: Measure first; the serialization overhead will dominate small tasks.
Leaving SharedWorker ports open on page unload
Fix: Close ports explicitly when the page unloads so the shared worker can terminate.
Key Takeaways
- Workers are fully isolated JavaScript environments β no DOM, own event loop, connected only by messages.
- Dedicated workers pair naturally with OffscreenCanvas and createImageBitmap for media work on a spare thread.
- Structured clone copies; transfer moves. Use transfer lists for large binary payloads.
- Design a typed message protocol with request ids before the codebase grows past a dozen calls.
- SharedWorkers coordinate across tabs through ports; manage port lifecycle deliberately.
- Offload only CPU-bound work longer than a frame budget β everything else belongs on the main thread.