Web Workers: Running JavaScript Off the Main Thread
Web workers keep the main thread responsive: module workers, postMessage, transferable objects, their limits, and when they are not worth it.

A user uploads a 40 MB CSV into a reporting tool. The upload finishes, the parser starts, and for four seconds the page does not respond: the spinner stops spinning, clicks queue up, the browser offers to kill the tab. The parsing code is correct. It is just running in the one place where every millisecond is shared with everything the user can see.
A Web Worker is a script that runs in a background thread, created from the page with new Worker(). It has its own global scope and event loop, no access to document or window, and communicates with the page by passing messages. The most common kind, the dedicated worker, belongs to the page that created it. Workers are the browser’s mechanism for real parallelism; I covered how that differs from asynchronous concurrency in concurrency and parallelism in JavaScript.
Why does the main thread matter?
Browsers consider any task over 50 milliseconds a “long task”, because it can delay the response to a click or keypress noticeably. Google’s Interaction to Next Paint metric, which is set to replace First Input Delay as a Core Web Vital in March 2024, measures exactly this: how long the page takes to show a visual response after the user interacts. Long JavaScript tasks are the most common cause of poor INP, and a worker removes them from the main thread entirely rather than just breaking them up.
How do you write a first worker?
// main.js
const worker = new Worker(new URL("./parse-worker.js", import.meta.url), { type: "module" });
worker.addEventListener("message", (event) => {
renderTable(event.data.rows);
});
worker.addEventListener("error", (event) => {
console.error("Worker failed:", event.message);
});
fileInput.addEventListener("change", async () => {
const text = await fileInput.files[0].text();
worker.postMessage({ type: "parse", text });
});
// parse-worker.js
import { parseCsv } from "./csv.js";
self.addEventListener("message", (event) => {
if (event.data.type === "parse") {
const rows = parseCsv(event.data.text);
self.postMessage({ rows });
}
});
The { type: "module" } option lets the worker use import statements. Module workers became available in every major browser when Firefox 114 shipped them in June 2023, so you no longer need importScripts() or a separate bundle. The new URL(..., import.meta.url) pattern is also recognized by Vite and webpack 5, which bundle the worker file automatically.
While the worker parses, the main thread is free: the spinner animates, the user can scroll and cancel. When the worker finishes, the result arrives as a message and the page renders it.
How does data cross the worker boundary?
Messages are not shared; they are copied with the structured clone algorithm. It handles objects, arrays, Maps, Sets, Dates, typed arrays, Blobs and Files, but not functions, DOM nodes or class instances’ prototypes (they arrive as plain objects). Copying is fast for small messages and expensive for large ones: sending a 50 MB array means duplicating 50 MB.
Transfer instead of copy
Some objects, including ArrayBuffer, ImageBitmap, MessagePort and OffscreenCanvas, can be transferred. Ownership moves to the receiver in constant time, and the sender’s copy becomes unusable.
const pixels = new Uint8ClampedArray(width * height * 4);
// Transfer the underlying buffer instead of copying it
worker.postMessage({ pixels, width, height }, [pixels.buffer]);
console.log(pixels.byteLength); // 0: the buffer now belongs to the worker
For image processing, audio, compression and anything else with large binary data, transfer is the difference between a worker that helps and one that just moves the cost into copying.
Making workers feel like functions
Raw postMessage gets messy once you have several kinds of request in flight. A small wrapper gives each request an ID and returns a promise:
// worker-client.js
export function createWorkerClient(url) {
const worker = new Worker(url, { type: "module" });
const pending = new Map();
let nextId = 0;
worker.addEventListener("message", ({ data }) => {
const { id, result, error } = data;
const entry = pending.get(id);
if (!entry) return;
pending.delete(id);
error ? entry.reject(new Error(error)) : entry.resolve(result);
});
return {
call(method, ...args) {
const id = nextId++;
return new Promise((resolve, reject) => {
pending.set(id, { resolve, reject });
worker.postMessage({ id, method, args });
});
},
terminate: () => worker.terminate(),
};
}
// usage
const search = createWorkerClient(new URL("./search-worker.js", import.meta.url));
const hits = await search.call("query", "wireless headphones");
Google’s Comlink library does the same with less code, using proxies so that calling a worker method looks exactly like calling a local async function. For one or two workers, the hand-written version is about 30 lines and has no dependency.
What can a worker use, and what can it not?
| Available in a worker | Not available |
|---|---|
fetch, WebSocket, EventSource |
document and every DOM API |
| IndexedDB, Cache API | window; the global is self |
crypto.subtle, TextEncoder, CompressionStream |
localStorage and sessionStorage |
OffscreenCanvas, createImageBitmap |
alert, confirm, prompt |
setTimeout, setInterval, requestAnimationFrame in dedicated workers |
Direct access to the page’s variables |
| WebAssembly | Synchronous access to the main thread |
The canvas row is worth highlighting: with OffscreenCanvas, a worker can render charts or animations directly, as described in the canvas element guide. Note that Web Storage is not available in workers, as covered in the Web Storage guide; use IndexedDB there.
Which jobs suit a worker?
Good fits:
- Parsing large CSV, JSON, XML or Markdown files.
- Client-side search: building and querying an index over thousands of records.
- Image processing: resizing, filters, compression before upload.
- Syntax highlighting and diffing of large documents.
- Encryption, hashing and compression.
- Running WebAssembly modules such as SQLite or image codecs.
Poor fits:
- Small, quick tasks. Posting a message has overhead, roughly in the range of a millisecond for typical payloads. For work that takes 5 milliseconds, the round trip costs more than it saves.
- DOM-heavy work. The worker cannot touch the DOM, so rendering a huge list still happens on the main thread. Virtualize the list instead.
- Waiting on the network.
fetchis already asynchronous; moving it to a worker does not make the page more responsive unless you also do heavy processing on the response.
Other kinds of workers
| Type | Lifetime and scope | Use for |
|---|---|---|
| Dedicated worker | Belongs to one page | Offloading computation |
| Shared worker | Shared by all same-origin pages that connect to it | One WebSocket connection or cache shared across tabs; not available in Chrome for Android |
| Service worker | Installed per origin, runs between the page and the network, even with no page open | Offline support, caching, push notifications |
Service workers are a different tool despite the name: they are network proxies, not a way to speed up computation on the page.
Scaling up with a pool
Each worker is one thread. For work that splits into independent chunks, such as processing 500 images, create a small pool of workers sized to navigator.hardwareConcurrency (minus one for the main thread) and hand out chunks as workers become free. Each worker has a memory cost of several megabytes, so do not create hundreds, and call terminate() on workers you no longer need.
Truly shared memory between threads is possible with SharedArrayBuffer and Atomics, but browsers only allow it on cross-origin isolated pages, which requires the Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers. Most apps never need it; message passing with transfers is simpler and fast enough.
Frequently Asked Questions
What is a Web Worker?
A Web Worker is a JavaScript script that runs on a background thread, separate from the page’s main thread. It cannot access the DOM, and it communicates with the page by sending and receiving messages, which keeps heavy computation from freezing the user interface.
Can a Web Worker access the DOM?
No. Workers have no access to document, window or any DOM API. They compute results and send them back to the main thread with postMessage, and the main thread updates the page.
When should I use a Web Worker?
Use one for CPU-heavy work that does not need the DOM and takes long enough to block the page, roughly more than 50 milliseconds: parsing large files, searching large datasets, image processing, compression and encryption. For small tasks, the messaging overhead outweighs the benefit.
What is the difference between a Web Worker and a Service Worker?
A dedicated Web Worker runs computation for a single page and stops when the page closes. A Service Worker sits between your site and the network, can run when no page is open, and handles caching, offline support and push notifications.
Keep the main thread for the user
The main thread is the only thread that can respond to the user, so every millisecond of computation spent there is a millisecond the interface cannot react. Find the long tasks in a performance profile, move the DOM-free ones into a module worker, transfer large buffers instead of copying them, and wrap the messaging in promises so the rest of the code barely notices the move. For the full reference, see the MDN Web Workers API guide and web.dev on Interaction to Next Paint. Related reading on this site: performance-safe CSS.
Originally posted on 11 October 2023 and post last modified on 11 October 2023