Skip to content
jshacks.dev
Async

Web Workers for Parallel Work in the Browser

Learn how Web Workers run JavaScript on a separate thread, how to send messages and transfer buffers, and when a worker keeps your page responsive.

6 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, Google Chrome and RabbitMQ logos.

A page that sorts a million rows, parses a large file or resizes an image on the main thread freezes while it does, because the main thread is also the thread that handles clicks, scrolls and painting. A Web Worker moves that work to another thread. The worker has its own event loop and its own memory, communicates with the page by passing messages and cannot touch the DOM. That restriction is the price of safety, and it is why workers suit computation and not interface updates. This post builds a worker in current Chrome, Firefox and Safari, shows how to send messages, return results and report errors, explains structured cloning and transferable objects, introduces SharedArrayBuffer and its headers and gives guidance on pooling and on when not to use a worker. The Node.js equivalent, worker_threads, follows the same ideas and is mentioned where it differs.

A first worker

Two files: the page and the worker script.

JavaScript
// main.js
const worker = new Worker(new URL("./sum-worker.js", import.meta.url), { type: "module" });

worker.addEventListener("message", (event) => {
  console.log("sum from worker:", event.data);
  worker.terminate();
});

worker.postMessage({ count: 1_000_000 });
console.log("message sent, page stays responsive");
JavaScript
// sum-worker.js
self.addEventListener("message", (event) => {
  let total = 0;
  for (let i = 1; i <= event.data.count; i++) total += i;
  self.postMessage(total);
});
Text
message sent, page stays responsive
sum from worker: 500000500000

The line after postMessage printed first, because the worker runs on its own thread and the page did not wait. The sum of 1 to 1,000,000 is 500,000,500,000. Using new URL(..., import.meta.url) lets bundlers find and build the worker file, and type: "module" allows import inside it. worker.terminate() stops it immediately, and a worker can also stop itself with self.close().

What a worker can and cannot do

Workers have fetch, setTimeout, IndexedDB, WebSocket, crypto, OffscreenCanvas, WebAssembly and importScripts or module imports. They have no document, no window and no DOM access. The global object is self, a DedicatedWorkerGlobalScope. Anything that updates the page goes through the main thread, usually by posting the result back and letting the page apply it.

Messages and structured cloning

postMessage copies the value using the structured clone algorithm. It handles numbers, strings, dates, maps, sets, typed arrays, plain objects and arrays and even cycles. It cannot clone functions, DOM nodes or class instances with their methods. A class instance arrives as a plain object holding its own data properties.

JavaScript
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  length() {
    return Math.hypot(this.x, this.y);
  }
}

const copy = structuredClone(new Point(3, 4));

console.log(copy);
console.log(copy instanceof Point);
console.log(typeof copy.length);
Text
{ x: 3, y: 4 }
false
undefined

structuredClone is the same algorithm that postMessage applies, so you can test what will survive without a worker. Methods and the prototype are gone, and sending a function throws a DataCloneError. Send plain data, and rebuild objects on the receiving side.

Copying has a cost proportional to the size of the data. For small messages it is negligible, and for tens of megabytes it is noticeable, which leads to transfers.

Transferring instead of copying

An ArrayBuffer can be transferred: ownership moves to the worker, nothing is copied and the buffer becomes unusable, with length zero, in the sender.

JavaScript
const buffer = new ArrayBuffer(8 * 1024 * 1024);

console.log("before:", buffer.byteLength);

worker.postMessage({ buffer }, [buffer]);

console.log("after:", buffer.byteLength);
Text
before: 8388608
after: 0

The second argument lists the objects to transfer. After the call the sender's buffer is detached. ImageBitmap, OffscreenCanvas, MessagePort and streams are transferable too. For image work, drawing on an OffscreenCanvas in a worker keeps the whole pipeline off the main thread.

Errors and request-reply

An exception thrown in a worker fires an error event on the Worker object in the page.

JavaScript
const worker = new Worker(new URL("./bad-worker.js", import.meta.url), { type: "module" });

worker.addEventListener("error", (event) => {
  console.log("worker failed:", event.message);
  event.preventDefault();
});
Text
worker failed: Uncaught Error: bad input

The message wording varies between browsers. For request and reply, where you send a job and expect one result, wrap the worker in a promise and match replies with an id.

JavaScript
function createWorkerClient(worker) {
  let nextId = 1;
  const pending = new Map();

  worker.addEventListener("message", ({ data }) => {
    const { resolve, reject } = pending.get(data.id);
    pending.delete(data.id);
    if (data.error) reject(new Error(data.error));
    else resolve(data.result);
  });

  return (payload) =>
    new Promise((resolve, reject) => {
      const id = nextId++;
      pending.set(id, { resolve, reject });
      worker.postMessage({ id, payload });
    });
}

const call = createWorkerClient(worker);
console.log(await call({ count: 10 }));
Text
55

This assumes a worker that replies with { id, result } for each { id, payload }. The wrapper makes the worker look like an async function, which is the shape most application code wants. Libraries such as Comlink generate this layer automatically from an exposed object.

Shared memory

SharedArrayBuffer gives several threads views of the same memory, with Atomics for synchronization. Because of the side-channel attacks known as Spectre, browsers expose it only on pages that are cross-origin isolated, which you opt into with two response headers.

Text
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp

With the headers set, crossOriginIsolated is true in the page and SharedArrayBuffer is defined. Without them, the constructor is missing, and code that depends on it fails at runtime. The headers affect how the page may load cross-origin resources, so apply them deliberately and test embeds and third-party scripts. SharedArrayBuffer and Atomics has its own post.

Worker types

A dedicated worker belongs to one page. A shared worker can serve several tabs of the same origin, which suits a single connection shared across tabs, though support has been uneven. A service worker is a different thing: it sits between the page and the network for offline support and push, and it is not for computation. Worklets, such as AudioWorklet, run small scripts in specialized threads.

Pooling

Starting a worker costs time and memory, because it loads its script and creates a new JavaScript realm. For many small jobs, create a fixed number of workers and send jobs to the idle one. A reasonable size is navigator.hardwareConcurrency - 1, leaving a core for the main thread.

JavaScript
const size = Math.max(1, (navigator.hardwareConcurrency ?? 4) - 1);
const pool = Array.from({ length: size }, () => new Worker("./worker.js", { type: "module" }));

let next = 0;
const pick = () => pool[next++ % pool.length];

console.log("pool size is at least 1:", pool.length >= 1);
Text
pool size is at least 1: true

Round-robin is the simplest policy. A queue that hands a job to whichever worker becomes idle first balances uneven jobs better.

When not to use a worker

Skip a worker when the job takes only a few milliseconds, since messaging and startup cost as much as the work. Skip it when the task needs the DOM, since you would have to send every read and write across threads. And skip it when the real cost is waiting on the network, since fetch already runs off the main thread. Good candidates are parsing large JSON or CSV, compressing, hashing, image and audio processing, search indexing, syntax highlighting of long documents and running WebAssembly modules.

Before reaching for a worker, try cheaper fixes. Chunk the work with scheduler.yield() so input is handled in between, or move it to idle time. A worker is the heavy tool for work that cannot be made small.

Debugging

Developer tools list workers as separate targets with their own console and breakpoints. A common surprise is that console.log from a worker appears in the same console, labeled with the worker's file name. Another is that a module worker silently fails to start if the script URL is wrong, and the failure appears as an error event with little detail, so check the Network panel for a 404.

Also inBrowser
Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.