Catalog My learning Blog
Frontend Developer Course: 100 Concepts in 100 Days · Phase 9 · Lesson 90 · 6 min read

Web Workers Explained: Off the Main Thread

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: Parsing and Aggregating a Large CSV in a Worker with Comlink
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Run CPU-heavy JavaScript in dedicated workers so the main thread stays responsive, communicate efficiently with postMessage, transferable objects and libraries such as Comlink, recognize which tasks suit workers, and understand shared workers, OffscreenCanvas and WebAssembly as related tools.

Concept Explanation

JavaScript on a page runs on the main thread together with rendering and input handling (Day 5), so any expensive computation competes directly with responsiveness. Splitting long tasks and yielding (Day 84) helps when the work can be divided, but some work is simply large: parsing a 20 megabyte JSON or CSV file, filtering and aggregating hundreds of thousands of records, generating a PDF, diffing documents, running a syntax highlighter on a large file, compressing images or running a machine learning model. For that work, the browser offers real parallelism through Web Workers.

A dedicated worker is a separate JavaScript thread with its own global scope and event loop, created with new Worker and a script URL, usually as a module with type module. It has no access to the DOM, window or document, but it can use fetch, IndexedDB, WebSockets, timers, crypto, WebAssembly and most computation APIs. The page and the worker communicate only by passing messages with postMessage and listening for message events. Because the worker runs on its own thread, a five second computation inside it leaves the page fully interactive, and on multi-core devices it actually runs in parallel.

Messages are copied with the structured clone algorithm (Day 39), which handles most data but costs time proportional to the data size, and copying a large result can itself create a long task. Transferable objects avoid the copy: ArrayBuffers, ImageBitmaps, MessagePorts and streams can be transferred, which moves ownership to the other thread almost instantly, leaving the sender's copy detached. SharedArrayBuffer allows true shared memory with Atomics for synchronization, but it requires the page to be cross-origin isolated with COOP and COEP headers because of Spectre-class attacks. For most applications, sending compact inputs and results and transferring large binary data is enough.

Raw postMessage code quickly becomes a hand-written protocol of message types and ids. Comlink, a small library from the Chrome team, wraps a worker in a proxy so the page calls worker functions as if they were async functions, and bundlers such as Vite support importing worker modules directly with the new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' }) pattern, so workers are bundled and typed like the rest of the code.

Not everything belongs in a worker. Work that is short, needs the DOM or is dominated by message transfer is better on the main thread. Rendering cannot move to a worker except for canvas drawing, which OffscreenCanvas allows: a chart or game can render entirely in a worker. Shared workers let several tabs of the same origin use one worker, useful for a single WebSocket connection shared across tabs. Service workers (Day 70) are a different kind of worker focused on network interception, not computation. WebAssembly can make the computation itself faster and is often run inside a worker, combining both benefits.

NeedToolNote
Heavy computationDedicated Web WorkerNo DOM access, message passing
Large binary dataTransferable ArrayBufferMoves ownership, no copy
Simple async API over a workerComlinkCalls look like async functions
Canvas rendering off threadOffscreenCanvas in a workerCharts, games, image processing
One connection for many tabsSharedWorkerSame origin tabs share it
True shared memorySharedArrayBuffer and AtomicsRequires cross-origin isolation
Faster computationWebAssembly, often in a workerCompiled code from Rust, C, Go
Network interceptionService workerDifferent purpose, not for compute

Worked Example: Parsing and Aggregating a Large CSV in a Worker with Comlink

The page stays responsive while the worker parses a large file and computes aggregates. The file's bytes are transferred instead of copied, and the progress callback crosses the thread boundary through Comlink.

TypeScript
// analytics.worker.ts: runs on its own thread
import * as Comlink from 'comlink';

type Totals = { rows: number; revenueCents: number; byRegion: Record<string, number> };

const api = {
  async aggregate(buffer: ArrayBuffer, onProgress: (pct: number) => void): Promise<Totals> {
    const text = new TextDecoder().decode(buffer);
    const lines = text.split('\n');
    const totals: Totals = { rows: 0, revenueCents: 0, byRegion: {} };
    for (let i = 1; i < lines.length; i++) {                       // skip the header row
      const [region, cents] = lines[i].split(',');
      if (!region) continue;
      const value = Number(cents) || 0;
      totals.rows++;
      totals.revenueCents += value;
      totals.byRegion[region] = (totals.byRegion[region] ?? 0) + value;
      if (i % 50_000 === 0) onProgress(Math.round((i / lines.length) * 100));
    }
    return totals;                                                  // small result, cheap to copy back
  },
};
export type AnalyticsApi = typeof api;
Comlink.expose(api);
TypeScript
// ReportUpload.tsx: the main thread only handles UI
import * as Comlink from 'comlink';
import type { AnalyticsApi } from './analytics.worker';

const worker = new Worker(new URL('./analytics.worker.ts', import.meta.url), { type: 'module' });
const analytics = Comlink.wrap<AnalyticsApi>(worker);

export function ReportUpload() {
  const [progress, setProgress] = useState(0);
  const [totals, setTotals] = useState<Totals | null>(null);

  async function onFile(file: File) {
    const buffer = await file.arrayBuffer();
    const result = await analytics.aggregate(
      Comlink.transfer(buffer, [buffer]),                           // move the bytes, do not copy them
      Comlink.proxy((pct: number) => setProgress(pct)),             // callback runs on the main thread
    );
    setTotals(result);
  }

  return (
    <>
      <input type="file" accept=".csv" onChange={(e) => e.target.files?.[0] && onFile(e.target.files[0])} />
      <progress value={progress} max={100} aria-label="Processing file" />
      {totals && <RegionChart data={totals.byRegion} />}
    </>
  );
}

With a 50 megabyte file, the main thread version freezes the page for several seconds, and the Performance panel shows one enormous task. The worker version shows the work on a separate worker track while the main thread keeps handling input and updating the progress bar.

The page transfers the file's bytes to a worker instead of copying them. The worker parses and aggregates on its own thread, sending progress through a proxied callback, and returns a small result. The main thread keeps handling input the whole time.
The page transfers the file's bytes to a worker instead of copying them. The worker parses and aggregates on its own thread, sending progress through a proxied callback, and returns a small result. The main thread keeps handling input the whole time.

Real-World Examples

  • Figma runs its rendering engine, written in C++ and compiled to WebAssembly, separately from its interface code, and Google's Squoosh image compression app uses Web Workers with WebAssembly codecs so that compressing an image never freezes the interface.
  • Comlink was created by Surma on the Google Chrome team to make workers practical by removing the boilerplate of message passing, and the Partytown library by Builder.io uses workers to run third-party scripts such as analytics off the main thread to improve responsiveness.
Key TakeawaysWeb Workers run JavaScript on separate threads, so heavy parsing, aggregation, compression and similar computation never blocks input or rendering. Communicate through messages, transfer large binary data instead of copying it, use Comlink and bundler worker imports for ergonomic, typed APIs, and choose OffscreenCanvas, SharedWorker, SharedArrayBuffer or WebAssembly for their specific needs. Keep short or DOM-bound work on the main thread.

Review Questions & Answers

It can run arbitrary JavaScript computation, use fetch, IndexedDB, WebSockets, timers, crypto and WebAssembly, and communicate with the page through messages. It cannot access the DOM, window or document, so it cannot update the interface directly.

Normally postMessage copies data with structured clone, which takes time proportional to its size. Transferring an ArrayBuffer or other transferable object moves ownership to the receiving thread almost instantly without copying, and the sender can no longer use it.

Shared memory enables high-resolution timers that can be used in Spectre-style side-channel attacks to read data from other origins. Requiring COOP and COEP headers ensures the page does not share a process with untrusted cross-origin content.

When the work is short, needs to read or write the DOM, or when the cost of sending large inputs and outputs between threads is comparable to the work itself. In those cases yielding on the main thread or optimizing the algorithm is better.