Workers run JavaScript on a separate thread with its own event loop and global scope, communicating with the page by message passing (postMessage). Their main purpose is to keep CPU-heavy work off the main thread so input, animation and rendering stay responsive. Workers cannot touch the DOM. There are three kinds: dedicated workers (one page), shared workers (several tabs of one origin) and service workers (a network proxy for offline support, caching and push).
// main.js
const worker = new Worker(new URL('./parse.worker.js', import.meta.url), { type: 'module' });
worker.postMessage({ csv: hugeCsvString });
worker.onmessage = (e) => renderTable(e.data.rows);
worker.onerror = (e) => console.error('worker failed', e.message);
// parse.worker.js
self.onmessage = (e) => {
const rows = e.data.csv.split('\n').map((line) => line.split(','));
self.postMessage({ rows });
};
Parsing a 50 MB file here no longer freezes scrolling or typing. That directly improves INP (Interaction to Next Paint).
OffscreenCanvas (canvas.transferControlToOffscreen()), e.g. charts and maps.postMessage copies data with the structured clone algorithm (supports Map, Date, typed arrays and cycles; not functions, DOM nodes or class prototypes).const buffer = new ArrayBuffer(64 * 1024 * 1024);
worker.postMessage(buffer, [buffer]);
buffer.byteLength; // 0 on the main thread now
SharedArrayBuffer + Atomics allow true shared memory, but require cross-origin isolation (Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp).postMessage in a promise/RPC interface so you can await api.parse(csv).| Dedicated | Shared | Service | |
|---|---|---|---|
| Scope | One page | All same-origin pages that connect | Controls pages in its scope |
| Lifetime | Lives with the page | While any client is connected | Event-driven; browser starts/stops it |
| Typical use | Heavy computation | Shared connection/state across tabs | Offline caching, request interception, push, background sync |
Note: SharedWorker is available in all modern desktop browsers and Safari, but not in Chrome for Android.
window. Workers do have fetch, IndexedDB, WebSocket, timers, crypto and OffscreenCanvas.new Worker(new URL(..., import.meta.url), { type: 'module' }) pattern so Vite/webpack can detect and bundle the worker.error and messageerror events, and terminate stuck workers with worker.terminate().scheduler.yield() or chunking may be enough. Workers are for genuinely parallel work.SharedArrayBuffer and the isolation headers it needs.Spotted a mistake or a rights concern? Report an issue