How to Offload Work to a Web Worker
Offload work to a web worker to keep the page responsive: postMessage, module workers, transferables, Comlink-style RPC, error handling, pools and limits.

JavaScript in the browser runs on one thread that also handles clicks, scrolling, layout and painting. Ask it to parse a large file, filter a hundred thousand rows or compress an image, and for the length of that task the page does not respond: buttons feel dead, animations stop and input lags. A web worker is a separate thread with its own event loop that runs a script in parallel, so heavy work goes there and the main thread keeps drawing. Workers cannot touch the DOM, communicate by messages and have costs that make them wrong for tiny tasks, but for the right job they turn a frozen page into a smooth one. This guide shows how to offload work to a web worker in JavaScript: when to use one, creating a worker and exchanging messages, module workers with imports, structured cloning and transferable objects to avoid copying, a promise-based wrapper, error handling and termination, progress reporting, worker pools, what workers can and cannot do, other kinds of workers and how to measure the benefit. The API is documented on MDN and works in every current browser.
When a worker helps
A worker helps when a task is CPU bound and takes more than about 50 milliseconds, the point at which people can feel the page stall: parsing or generating big data, searching and sorting large arrays, image and audio processing, cryptography, compression, running a WebAssembly module, syntax highlighting a large document. A worker does not speed up waiting for the network, since fetch is already asynchronous and does not block the thread, and it adds overhead for tiny tasks, where messaging costs more than the work. Measure first with the Performance panel: long tasks in the main thread are the sign.
A first worker
A worker is a script file. The page creates it with new Worker(url), sends messages with postMessage() and receives them in the message event. Inside the worker, self is the global scope, and onmessage receives input.
const worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
worker.addEventListener("message", (event) => {
console.log("sum from worker:", event.data);
});
worker.postMessage({ numbers: Array.from({ length: 1_000_000 }, (_, i) => i) });
console.log("main thread keeps running");self.addEventListener("message", (event) => {
const { numbers } = event.data;
let sum = 0;
for (const n of numbers) sum += n;
self.postMessage(sum);
});main thread keeps running
sum from worker: 499999500000The line after postMessage runs immediately, and the result arrives later as an event. The new URL(..., import.meta.url) form lets bundlers and browsers find the worker file relative to the current module. With type: "module" the worker can use import and export, which current browsers all support.
What gets copied
Messages are copied with the structured clone algorithm, which handles objects, arrays, maps, sets, dates, typed arrays, Blob, File and more, and rejects functions, DOM nodes and class instances' methods. A million-element array is copied in full on every message, which costs time and memory, and for big data the copy can cost more than the work. Two techniques avoid it.
Transferable objects move ownership of the underlying memory instead of copying it. An ArrayBuffer listed in the transfer list is moved to the worker for free and becomes unusable on the sending side.
const buffer = new Float64Array(5_000_000).buffer;
console.log(buffer.byteLength);
worker.postMessage({ buffer }, [buffer]);
console.log(buffer.byteLength);40000000
0After the transfer the sender's buffer has length zero, which shows it moved. The worker can transfer it back with its result. ImageBitmap, OffscreenCanvas, MessagePort and streams are transferable as well.
SharedArrayBuffer shares memory between threads, with Atomics for safe access. It requires the page to be cross-origin isolated, with the headers Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp, and it is meant for advanced cases such as parallel algorithms, where careful synchronization is the price.
A promise-based wrapper
Raw postMessage is a one-way channel, so matching a response to a request needs an id. A tiny wrapper turns the worker into an async function.
function createWorkerClient(url) {
const worker = new Worker(url, { type: "module" });
const pending = new Map();
let nextId = 1;
worker.addEventListener("message", ({ data }) => {
const { id, result, error } = data;
const entry = pending.get(id);
if (!entry) return;
pending.delete(id);
if (error) entry.reject(new Error(error));
else entry.resolve(result);
});
return {
call(method, params, transfer = []) {
const id = nextId++;
return new Promise((resolve, reject) => {
pending.set(id, { resolve, reject });
worker.postMessage({ id, method, params }, transfer);
});
},
terminate: () => worker.terminate(),
};
}
const client = createWorkerClient(new URL("./math-worker.js", import.meta.url));
console.log(await client.call("sum", [1, 2, 3]));const methods = {
sum: (numbers) => numbers.reduce((a, b) => a + b, 0),
sort: (numbers) => [...numbers].sort((a, b) => a - b),
};
self.addEventListener("message", async ({ data }) => {
const { id, method, params } = data;
try {
const result = await methods[method](params);
self.postMessage({ id, result });
} catch (error) {
self.postMessage({ id, error: error.message });
}
});6Each call gets a number, the worker echoes the number with its answer and the wrapper resolves the right promise. The library Comlink provides the same idea with a proxy, so that you call worker functions as if they were local, in about a kilobyte.
Errors and termination
An uncaught error in the worker fires an error event on the Worker object in the page, with the message and location. A message that cannot be cloned fires messageerror. Handle both, or a failed worker leaves promises pending forever.
worker.addEventListener("error", (event) => {
console.error("worker error:", event.message, event.filename, event.lineno);
for (const { reject } of pending.values()) reject(new Error("Worker crashed"));
pending.clear();
});
worker.addEventListener("messageerror", () => {
console.error("a message could not be deserialized");
});worker error: Uncaught ReferenceError: foo is not defined worker.js 4Call worker.terminate() from the page to stop a worker immediately, with no chance for cleanup, or self.close() from inside. Terminate when the work is cancelled, and when the component using the worker is destroyed, since an idle worker still holds memory. For cancellation of a long job without killing the worker, check a shared flag, or split the work into slices and check for a cancel message between them.
Report progress
A long task should tell the page how far it has come. The worker sends progress messages while it works, and the final result at the end. Yield occasionally so that incoming messages, such as a cancel request, are processed, because a tight loop blocks the worker's own event loop.
// worker
self.addEventListener("message", async ({ data }) => {
const { rows } = data;
const out = [];
for (let i = 0; i < rows.length; i++) {
out.push(transform(rows[i]));
if (i % 5000 === 0) {
self.postMessage({ type: "progress", done: i, total: rows.length });
await new Promise((resolve) => setTimeout(resolve, 0));
}
}
self.postMessage({ type: "done", result: out });
});(the page receives a progress message every 5000 rows, then the result)On the page, update a <progress> element from the progress messages. Awaiting a zero-delay timer lets the worker handle a pending cancel message between slices.
A pool of workers
One worker uses one core. To process many independent items in parallel, create a pool sized to the hardware, and distribute tasks. navigator.hardwareConcurrency reports the number of logical processors; leave one free for the main thread.
class WorkerPool {
constructor(url, size = Math.max(1, (navigator.hardwareConcurrency ?? 4) - 1)) {
this.idle = Array.from({ length: size }, () => createWorkerClient(url));
this.queue = [];
}
run(method, params) {
return new Promise((resolve, reject) => {
this.queue.push({ method, params, resolve, reject });
this.#drain();
});
}
#drain() {
while (this.idle.length && this.queue.length) {
const client = this.idle.pop();
const task = this.queue.shift();
client
.call(task.method, task.params)
.then(task.resolve, task.reject)
.finally(() => {
this.idle.push(client);
this.#drain();
});
}
}
}
const pool = new WorkerPool(new URL("./math-worker.js", import.meta.url), 4);
const results = await Promise.all([1, 2, 3, 4, 5].map((n) => pool.run("sum", [n, n])));
console.log(results);[ 2, 4, 6, 8, 10 ]Each worker takes a task when idle and returns to the pool when done, so five tasks run on four workers with one queued. Creating workers costs tens of milliseconds and some memory each, so create the pool once and reuse it.
What workers cannot do
A worker has no access to window, document or the DOM, so it cannot read or change the page. It has fetch, setTimeout, indexedDB, WebSocket, crypto, TextEncoder, URL, Intl and importScripts() in classic workers, plus OffscreenCanvas for drawing without the DOM. It cannot use localStorage. The same-origin policy applies to the script file, so a worker must come from your origin, or be created from a Blob URL, for example for inline code, which has its own security considerations.
Other worker types
A dedicated worker serves one page. A shared worker, created with SharedWorker, can be connected to by several tabs of the same origin, which is useful for one socket shared by all tabs, with limited support on some mobile browsers. A service worker is a different kind, sitting between the page and the network for caching and push. Worklets, such as audio and paint worklets, run small pieces of code in rendering pipelines. Choose the one that fits, and for general computation use a dedicated worker.
Measure the benefit
A worker moves work off the main thread, and it does not make the work itself faster. Check by recording a trace before and after: the long task disappears from the main thread, and input latency improves. Compare total time too, as messaging and copying add overhead. Use performance.now() around the call, and check memory for big copies. For tasks under a few milliseconds, or those that must update the DOM at every step, keep them on the main thread, and consider breaking work into chunks with scheduler.yield() or requestIdleCallback() where a worker is not practical.


