Web Workers
Web Workers let you run JavaScript on a background thread, keeping the UI smooth even during heavy CPU-bound tasks. They communicate with the main thread via message passing and cannot access the DOM.
How do Web Workers make JavaScript faster?
Web Workers run JavaScript on a separate thread, so CPU-heavy work like parsing large files, image processing or complex calculations doesn't freeze the page. The main page and the worker communicate only by sending messages (postMessage and the message event); workers can't touch the DOM.
// main.js
const worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
worker.postMessage({ numbers: bigArray });
worker.onmessage = (e) => render(e.data);
// worker.js
self.onmessage = (e) => {
const sum = e.data.numbers.reduce((a, b) => a + b, 0);
self.postMessage(sum);
};Workers CAN Access
fetch() / XMLHttpRequestsetTimeout / setIntervalWebSocketsIndexedDBCache APICrypto API (SubtleCrypto)WebAssemblyimportScripts() for other scriptsself (the worker global scope)Workers CANNOT Access
DOM (document, window, document.body…)Any DOM API (querySelector, createElement…)localStorage / sessionStorageThe main thread's variables (no shared scope)alert() / confirm() / prompt()Canvas 2D rendering context (use OffscreenCanvas)parent/opener window referencesWhen to Use Web Workers
Parse multi-MB API responses without blocking UI
Resize, filter, compress images (with OffscreenCanvas)
Hashing, encryption, key derivation (SubtleCrypto)
Compute chart data, statistics from large datasets
Syntax highlighting, transpiling in the browser
Run WASM modules for physics, AI, compression
Common Pitfalls
Interactive Worker Demo
Code Editor
<button id="go">Find primes below 2,000,000 in a worker</button>
<p>The page stays responsive: <input placeholder="type here meanwhile"></p>
<p id="out"></p>Preview
Web Workers — step by step
The main thread bottleneck
The browser main thread handles JavaScript execution, layout, painting, and user input — all in a single thread. Long-running JavaScript (sorting 100k items, image processing, cryptography) blocks this thread, making the UI unresponsive. Web Workers run JavaScript in a separate OS thread, completely isolated from the main thread.
🎯 Quick Check
Which of these CAN a Web Worker do?
Web Workers: summary
Key points
- Messages are copied. Transfer an
ArrayBuffer(postMessage(buf, [buf])) to move it without copying. - Creating a worker has a cost; reuse workers for repeated tasks.
- Libraries like Comlink make workers feel like normal async function calls.
Frequently asked questions
›When should I use a Web Worker?
When a task takes more than about 50ms of CPU time and makes the page feel stuck. Network requests don't need workers; they're already asynchronous.