AI & LLMs

Web Worker: Run Heavy JavaScript Without Freezing the Page

Web Worker: Complete Guide to JavaScript Multithreading for Modern Web Applications
On this page
  1. What a web worker changes, measured
  2. A complete working example
  3. With Vite, webpack or another bundler
  4. The two rules that cause most errors
  5. 1. A worker cannot touch the page
  6. 2. Only data can be sent, not functions
  7. Transferable objects: moving data instead of copying it
  8. Worker pools, and why more workers can be slower
  9. Using a worker in React
  10. When a worker is the right tool
  11. Three kinds of worker
  12. Debugging a worker
  13. Frequently asked questions about web workers
  14. Oh hi there 👋It’s nice to meet you.
  15. Sign up to receive awesome content in your inbox.

JavaScript in the browser runs on one thread, the same one that handles clicks, scrolling and drawing the page. When your code runs a slow loop, everything else waits: buttons stop responding, animations stutter and the page looks frozen. A web worker fixes this by running that code on a separate background thread, leaving the main thread free to keep the interface smooth.

This guide shows a complete working example, with measurements taken in a real browser, then covers the parts that trip people up: the DOM restriction, data that cannot be sent, transferable objects, worker pools and cleaning up in React.

What a web worker changes, measured

Here is the same task, adding 60 million square roots, run two ways in Chromium. The second column counts animation frames rendered while the work was happening, which is how smooth the page looked:

Where the work ran Frames rendered during it Time
Main thread 2 — the page was frozen 133 ms blocked
Web worker 10 — the page kept painting 153 ms, result identical

Both produced exactly the same number. The worker took marginally longer in total, because starting the thread and passing messages costs a little, but the main thread stayed free the whole time. That is the trade: a small amount of extra total time in exchange for an interface that never freezes.

A blocking loop on the main thread compared with the same work in a web workerWithout a worker the main thread is blocked and almost no frames render; with a worker the task runs on a background thread and the page keeps painting.Main threadwithout a workerheavy loop: page frozenUI updates late2 frames renderedMain threadwith a workerpost the taskUI keeps paintingWorker threadbackgroundthe same loop runs here10 frames rendered, same result
Measured in a browser: a blocking loop stops the page painting; the same work in a worker does not.

A complete working example

A worker is a separate JavaScript file. It listens for messages, does its work and posts the result back:

// worker.js
self.onmessage = (event) => {
  const { count } = event.data;

  let total = 0;
  for (let i = 0; i < count; i++) {
    total += Math.sqrt(i);
  }

  self.postMessage({ total: Math.round(total) });
};

The page creates the worker, sends it a message and handles the reply:

// main.js
const worker = new Worker('worker.js');

worker.onmessage = (event) => {
  document.querySelector('#result').textContent = event.data.total;
  worker.terminate();                       // free the thread when the job is done
};

worker.onerror = (event) => {
  console.error('Worker failed:', event.message, event.filename, event.lineno);
};

worker.postMessage({ count: 60_000_000 });  // returns immediately; the page stays responsive

postMessage returns straight away. Your code continues, the browser keeps drawing, and the result arrives later through onmessage. Always add an onerror handler: without one, a mistake inside the worker fails silently and your result never arrives.

With Vite, webpack or another bundler

A plain path like 'worker.js' breaks once your files are bundled and renamed. Modern bundlers understand this form instead, which keeps the worker alongside your source file:

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

With type: 'module' the worker can use import statements, exactly like the rest of your code. If you see “Cannot use import statement outside a module” from a worker, that option is what is missing; the other causes are in fixing “Cannot use import statement outside a module”.

The two rules that cause most errors

1. A worker cannot touch the page

Workers have no access to the DOM, window or document. Trying anyway produces a clear error, captured in testing:

ReferenceError: document is not defined

That restriction is what makes workers safe: two threads changing the same page at once would cause race conditions. So a worker computes, and the main thread updates the interface with the result. Workers can use fetch, timers, IndexedDB, WebSocket and most other non-visual APIs.

2. Only data can be sent, not functions

Messages are copied with the structured clone algorithm, which handles objects, arrays, dates, maps, sets, typed arrays and more, but not functions, DOM nodes or class methods. Sending a function throws:

DataCloneError: Failed to execute 'postMessage' on 'Worker': () => 1 could not be cloned.

Send plain data, and keep the logic inside the worker file. If you need different behaviour, send a string such as { task: 'resize', width: 800 } and let the worker choose what to run.

Transferable objects: moving data instead of copying it

Structured cloning copies everything you send, which gets expensive with large binary data such as image pixels or audio buffers. A transferable object hands ownership to the worker instead, with no copy. The difference measured with a 32 MB buffer:

Method Time to send 32 MB Buffer in the sender afterwards
Structured clone (copy) 46.3 ms 33,554,432 bytes, still usable
Transfer (move) 1.1 ms 0 bytes, no longer usable
const buffer = new ArrayBuffer(32 * 1024 * 1024);

worker.postMessage({ buffer }, [buffer]);   // the second argument transfers it

console.log(buffer.byteLength);             // 0: ownership moved to the worker

About forty times faster here, with one condition: after transferring, the sender can no longer read that buffer. If you still need the data, keep a copy or have the worker transfer it back when it finishes.

Worker pools, and why more workers can be slower

For several independent tasks, you can run several workers. The sensible maximum is the number of processor cores the browser reports, available as navigator.hardwareConcurrency. Creating more than that does not add parallelism; it just adds overhead.

The test machine for this article reported 1 logical core, and the result shows exactly why the limit matters:

How 4 tasks ran Total time
One worker, one task at a time 191 ms
Four workers in parallel on 1 core 239 ms, slower

With only one core to share, the four workers took turns anyway and added startup cost. On a four-core laptop the parallel version would win. Size the pool from the device:

const size = Math.max(1, Math.min(navigator.hardwareConcurrency || 2, 4));
const pool = Array.from({ length: size }, () => new Worker(new URL('./worker.js', import.meta.url), { type: 'module' }));

Reuse those workers across tasks rather than creating one per task, and terminate them when the feature is closed.

Using a worker in React

Create the worker in an effect and terminate it in the cleanup, so it does not leak when the component unmounts or in development, where effects run twice on purpose:

import { useEffect, useRef, useState } from 'react';

export function HeavyTotal({ count }) {
  const [total, setTotal] = useState(null);
  const workerRef = useRef(null);

  useEffect(() => {
    const worker = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' });
    workerRef.current = worker;
    worker.onmessage = (event) => setTotal(event.data.total);
    worker.onerror = () => setTotal('could not calculate');
    return () => worker.terminate();        // cleanup: no stray threads
  }, []);

  useEffect(() => {
    workerRef.current?.postMessage({ count });
  }, [count]);

  return <p>{total ?? 'Calculating…'}</p>;
}

Why the cleanup matters, and why that effect runs twice while you develop, is explained in why useEffect runs twice.

Message passing with postMessage gets verbose once a worker has several jobs. The small library Comlink wraps a worker so you can call its functions as if they were local and await the result, which keeps the code readable.

When a worker is the right tool

Good fit Poor fit
Parsing or transforming large CSV and JSON files Waiting for network requests: fetch already does not block
Image and video processing, filters, thumbnails Anything that must change the DOM directly
Encryption, hashing, compression Work measured in a few milliseconds, where messaging costs more
Simulations, physics, pathfinding, large sorts Sending huge objects back and forth on every frame
Running machine learning models in the browser Simple state updates and rendering

A practical threshold: if a task regularly takes longer than about 50 ms, it is long enough for people to notice the page stall, and worth moving to a worker. Measure first with the Performance panel in your browser’s developer tools, which shows long tasks on the main thread in red.

Workers are not the only way to keep a page responsive. Breaking work into chunks, virtualizing long lists and debouncing and throttling frequent events often solve the problem with less complexity. Reach for a worker when the work itself is genuinely heavy and cannot be reduced.

Three kinds of worker

  • Dedicated worker: what this article uses. One page owns it, and it ends when you terminate it or the page closes.
  • Shared worker: one worker shared by several tabs or windows from the same site, which communicate through ports. Useful for a single shared connection, though browser support is narrower.
  • Service worker: a different tool despite the similar name. It sits between your site and the network to cache responses and enable offline use. It is not meant for heavy computation.

Debugging a worker

  • In Chrome DevTools, open the Sources panel: each worker appears as its own context where you can set breakpoints and step through code.
  • console.log inside a worker shows in the console, usually labelled with the worker’s file name.
  • The Performance panel records worker activity on its own track, so you can see whether the main thread really was free.
  • Loading a worker from a different origin is blocked by browser security. For a quick inline worker during development, build one from a blob: new Worker(URL.createObjectURL(new Blob([code], { type: 'application/javascript' }))).

Frequently asked questions about web workers

Does a web worker make my code faster?

Not by itself: the same work takes roughly the same time, as the measurements here show. What it changes is where that time is spent, so the page stays responsive. Running several tasks in parallel can be faster, but only up to the number of processor cores.

Why can’t a worker access the DOM?

Two threads changing the page at the same time would create race conditions, so the browser blocks it. A worker that touches document throws “document is not defined”. Send the result to the main thread and update the page there.

What is the difference between a web worker and a service worker?

A web worker runs computations in the background for one page. A service worker intercepts network requests to cache responses and enable offline use. They solve different problems.

How many workers should I create?

At most navigator.hardwareConcurrency, the number of logical cores. On the single-core machine tested here, four parallel workers were slower than running the tasks one after another.

Do I need to terminate a worker?

Yes, when you no longer need it. A running worker keeps its thread and memory. Call worker.terminate() from the page, or self.close() inside the worker, and always terminate in a React effect cleanup.

logo

Oh hi there 👋
It’s nice to meet you.

Sign up to receive awesome content in your inbox.

We don’t spam! Read our privacy policy for more info.

Saurabh Pathak

Saurabh Pathak is an AI engineer and MERN stack developer, and the founder of mernstackdev.com. He builds open-source projects such as the Haat gateway and MCP safety tooling, and he writes hands-on tutorials on React, Node.js, MongoDB and AI agents. He cares most about code that works in production.