Skip to the page

JavaScript cost and the main thread · mid

Moving work off the main thread with Web Workers

A Web Worker runs JavaScript on another thread with no DOM access, talking to the page by postMessage with structured-clone copies (or zero-copy transfers), so it suits CPU-heavy work like parsing, filtering, crypto and image processing.

The notes

What you must know

  • Workers have no DOM, no window, no React. They get messages and send results back.
  • postMessage copies data with the structured clone algorithm: Date, Map, Set, ArrayBuffer and plain objects copy fine; functions and DOM nodes throw DataCloneError; class instances lose their prototype (methods).
  • Copying big data has a cost. Transfer ArrayBuffers (postMessage(data, [buffer])) to move ownership with no copy; the sender's buffer becomes empty (byteLength 0).
  • Good uses: parsing large JSON/CSV, search indexing and filtering, diffing, compression, image processing, syntax highlighting. OffscreenCanvas lets a worker draw.
  • A library like Comlink hides postMessage behind async function calls.
  • Service workers are different: they sit between the page and the network (caching, offline, push), not a place for CPU-heavy work.

The red pen

Common traps: mistake → fix

  • Mistake: "structuredClone and postMessage keep methods"

    Fix: functions throw DataCloneError and class instances become plain objects.

  • Mistake: "Put React rendering in a worker"

    Fix: workers cannot touch the DOM; keep rendering on the main thread and move pure computation.

  • Mistake: "A Web Worker and a Service Worker are the same"

    Fix: a web worker is for computation for one page; a service worker is a network proxy for the whole origin.

Easy to hard

Questions interviewers ask, easy to hard

  1. What are Web Workers and what can't they do?
  2. How does data move between a worker and the page? What is a transferable?
  3. Web Worker vs Service Worker: what is each for?
  4. Our filter on 50,000 rows freezes the page. Would you use a worker, chunking, or both? Why?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview