Skip to content

Lesson 2 of 9 · 22m

Web Workers: CPU Work Without Freezing the UI

Workers are isolated threads with message passing, not shared-memory convenience — use transferable objects and workload boundaries deliberately.

JavaScript's main thread is not merely where rendering happens. It is where input handling, layout, painting preparation, timers, and your application logic all queue up. Run a 400 millisecond JSON parse or image transform there and the interface does not feel "a little slow"; it ignores clicks. Web workers exist so expensive computation can happen without stealing the user's thread.

A worker is a separate world

// main.js
const worker = new Worker("/workers/hash-worker.js", { type: "module" });
worker.postMessage({ fileBuffer }, [fileBuffer]);
worker.onmessage = event => renderDigest(event.data.digest);

// workers/hash-worker.js
self.onmessage = async event => {
  const digest = await crypto.subtle.digest("SHA-256", event.data.fileBuffer);
  self.postMessage({ digest });
};

There is no DOM in a worker. There is no shared object graph either. postMessage structured-clones data unless you transfer it, and cloning a 500 MB buffer is exactly the kind of accidental cost that makes people conclude "workers are slow."

Transfer, don't copy

Transferable objects — ArrayBuffer, MessagePort, OffscreenCanvas, streams — move ownership instead of copying bytes:

worker.postMessage({ pixels: imageData.data.buffer }, [imageData.data.buffer]);
// imageData.data.buffer is now detached in the sender.

This is one of the few places where JavaScript makes ownership visible. After transfer, the sender cannot read the buffer. Model that contract in your API or you will eventually transfer the same object twice and spend an afternoon wondering why everything is zero.

Good worker boundaries are coarse

The sweet spot is a self-contained job: parse a large file, compress an image, index text, verify signatures, crunch simulation steps. The bad shape is hundreds of tiny messages per frame. Serialization overhead, scheduling latency, and back-and-forth round trips can cost more than the computation.

For CPU-heavy interactive work, batch input and return progress. For rendering-adjacent work, OffscreenCanvas can move canvas painting into a worker, but Safari support and framework assumptions need checking before you commit.

Field notes

  • SharedArrayBuffer is powerful but cross-origin isolation requirements are strict; do not reach for it before batching messages.
  • Terminate workers when a view unmounts. A forgotten worker is a background CPU and memory leak with no DOM to inspect.
  • Errors inside workers do not automatically surface like normal page errors; attach worker.onerror and log structured context.
  • Bundlers have special worker syntax. Verify the generated URL in production, not only in dev.

Was this lesson helpful?

Sign in to rate