Asynchronous JavaScript

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() / XMLHttpRequest
setTimeout / setInterval
WebSockets
IndexedDB
Cache API
Crypto API (SubtleCrypto)
WebAssembly
importScripts() for other scripts
self (the worker global scope)

Workers CANNOT Access

DOM (document, window, document.body…)
Any DOM API (querySelector, createElement…)
localStorage / sessionStorage
The main thread's variables (no shared scope)
alert() / confirm() / prompt()
Canvas 2D rendering context (use OffscreenCanvas)
parent/opener window references

When to Use Web Workers

Large JSON parsing

Parse multi-MB API responses without blocking UI

Image processing

Resize, filter, compress images (with OffscreenCanvas)

Cryptography

Hashing, encryption, key derivation (SubtleCrypto)

Data visualization

Compute chart data, statistics from large datasets

Code compilation

Syntax highlighting, transpiling in the browser

WebAssembly tasks

Run WASM modules for physics, AI, compression

Common Pitfalls

Creating a new Worker on every button click — each worker has ~1-5ms startup cost and ~2-10 MB memory overhead
Create workers once and reuse them. Implement a worker pool for parallel tasks.
Sending large objects via postMessage — they're DEEP CLONED, doubling memory usage and taking time
Use Transferable objects (ArrayBuffer) with the transfer argument to move data at zero copy cost
Not calling worker.terminate() — leaked workers keep running and consuming memory
Always terminate workers when done, or when the parent component unmounts
Trying to pass DOM nodes, functions, or class instances to workers — they fail serialization silently
Only pass plain data (objects, arrays, typed arrays). Reconstruct class instances inside the worker.

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

1 / 4
1

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.

1 of 4
💡Use a worker pool for throughput
Creating and destroying workers has overhead. For repeated tasks, maintain a pool of 2-4 workers (matching CPU cores). Distribute tasks across the pool and reuse workers. Libraries like Comlink wrap workers in a Proxy so you can call worker functions as if they were async local functions, hiding the postMessage boilerplate entirely.

🎯 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.