Web Workers in JavaScript: Moving Heavy Work Off the Main Thread
A practical guide to Web Workers. Learn how dedicated and module workers work, how postMessage and structured cloning affect performance, when to use transferable objects, SharedArrayBuffer, and OffscreenCanvas, how to build worker pools, and how to integrate workers with Vite and React to improve INP.
Table of Contents
- Introduction
- Why the Main Thread Matters
- Your First Worker
- Module Workers
- What Workers Can and Can’t Do
- Messaging and Structured Cloning
- What Can Be Cloned
- The Cost of Copying
- Transferable Objects
- Request/Response Patterns
- Correlating Messages with IDs
- Using Comlink
- Error Handling and Cancellation
- Worker Pools
- SharedArrayBuffer and Atomics
- OffscreenCanvas
- Workers with Bundlers
- Using Workers in React
- When Not to Use a Worker
- Debugging Workers
- Common Pitfalls
- Best Practices
- Conclusion
Introduction
JavaScript in the browser runs on a single main thread that also handles rendering, layout, and user input. When your code parses a 20 MB JSON file, filters 100,000 rows, or resizes an image, nothing else can happen until it finishes. Clicks don’t register, animations freeze, and typing lags.
Web Workers fix this by running JavaScript on a separate thread. They’ve been supported in every browser for over a decade, yet many teams still reach for setTimeout chunking or simply accept the jank. Part of the reason is ergonomics: workers communicate through messages, which feels awkward next to normal function calls.
This guide covers how workers actually work, what moving data between threads costs, how to make workers feel like ordinary async functions, and how to integrate them with modern bundlers and React. If you need a refresher on why long tasks block the page in the first place, start with our guide to the JavaScript event loop.
Why the Main Thread Matters
The browser needs the main thread to respond to input and to produce frames. At 60 frames per second, each frame has about 16 ms of budget, and the browser needs some of that for itself. Any task longer than 50 ms is a long task, and long tasks directly hurt Interaction to Next Paint (INP), the Core Web Vital that measures responsiveness.
Here’s the kind of code that causes problems:
// ❌ Runs on the main thread and blocks for hundreds of millisecondssearchInput.addEventListener("input", (event) => { const query = (event.target as HTMLInputElement).value; const results = fuzzySearch(allProducts, query); // 300ms on 50k items renderResults(results);});There are three general ways to deal with expensive work:
| Approach | How it helps | Limitation |
|---|---|---|
| Do less work | Better algorithms, indexing, pagination, server-side work | Not always possible |
| Yield to the browser | Split work into chunks with scheduler.yield() or setTimeout | Total time is the same or longer; still competes with UI |
| Move work to another thread | Main thread stays free while work runs in parallel | Data must be copied or transferred between threads |
Workers are the third option. They don’t make the work faster, but they make it not block the UI, and on multi-core devices the work runs truly in parallel. For more on measuring and improving INP, see our Core Web Vitals guide.
Your First Worker
A dedicated worker is created from a separate script file. The main thread and the worker talk through postMessage and message events.
self.addEventListener( "message", (event: MessageEvent<{ products: Product[]; query: string }>) => { const { products, query } = event.data; const results = fuzzySearch(products, query); self.postMessage(results); },);const worker = new Worker(new URL("./search.worker.ts", import.meta.url), { type: "module",});
worker.addEventListener("message", (event: MessageEvent<Product[]>) => { renderResults(event.data);});
searchInput.addEventListener("input", (event) => { const query = (event.target as HTMLInputElement).value; worker.postMessage({ products: allProducts, query });});The search now runs in the background. The input stays responsive even while the worker is busy.
This version still has a performance problem, though: it sends the entire allProducts array on every keystroke. We’ll fix that in The Cost of Copying.
Module Workers
The { type: "module" } option makes the worker an ES module, so you can use import and export inside it:
import { fuzzySearch } from "./lib/fuzzy-search";import type { Product } from "./types";Module workers are supported in all modern browsers. Classic workers use importScripts() instead, which loads scripts synchronously and doesn’t support ES modules. There’s no reason to write classic workers in new code.
The new URL("./file.ts", import.meta.url) pattern is important. It resolves the worker path relative to the current module, and bundlers like Vite, webpack 5, Rollup, esbuild-based tools, and Parcel recognize it and bundle the worker as a separate entry point.
What Workers Can and Can’t Do
A worker runs in a DedicatedWorkerGlobalScope, not a Window. Many web APIs are available, but anything that touches the DOM is not:
| Available in workers | Not available in workers |
|---|---|
fetch, WebSocket, EventSource | document, DOM elements |
IndexedDB, Cache API | window, localStorage, sessionStorage |
crypto.subtle, TextEncoder, CompressionStream | alert, confirm |
setTimeout, setInterval, Promises | Direct access to main-thread variables |
OffscreenCanvas, createImageBitmap | Rendering to the page (except via OffscreenCanvas) |
| WebAssembly | Most UI-related APIs |
This shapes how you design worker code: keep pure computation and I/O in the worker, and keep everything that touches the DOM on the main thread.
Messaging and Structured Cloning
Workers don’t share memory with the main thread by default. When you call postMessage(data), the browser makes a structured clone of data: a deep copy that the other thread receives as a new, independent object.
What Can Be Cloned
The structured clone algorithm handles more than JSON:
worker.postMessage({ date: new Date(), // ✅ Preserved as a Date map: new Map([["a", 1]]), // ✅ Maps and Sets bytes: new Uint8Array([1, 2, 3]), // ✅ Typed arrays and ArrayBuffers blob: new Blob(["hello"]), // ✅ Blobs and Files regex: /abc/gi, // ✅ RegExps error: new Error("oops"), // ✅ Errors nested: { cyclic: null as unknown }, // ✅ Cyclic references are fine});Some things can’t be cloned and will throw a DataCloneError:
// ❌ Functionsworker.postMessage({ callback: () => {} });
// ❌ DOM nodesworker.postMessage({ element: document.body });
// ⚠️ Class instances lose their prototype and become plain objectsclass User { constructor(public name: string) {} greet() { return `Hi, ${this.name}`; }}worker.postMessage(new User("Ada")); // Arrives as { name: "Ada" }, no greet()The last point surprises people most. If your worker needs methods, send plain data and reconstruct the class on the other side.
You can also use structuredClone() directly on a single thread, which is now the standard way to deep-copy objects. We covered it alongside other comparison and copying techniques in how to check if two objects are equal.
The Cost of Copying
Cloning isn’t free. The browser serializes the data on the sending thread and deserializes it on the receiving thread, and the serialization part runs on the main thread when you send from there. Sending a 50 MB array of objects can block the main thread for longer than the work you were trying to offload.
The fix for our search example is to send the data once, keep it in the worker, and only send small messages afterward:
import { fuzzySearch } from "./lib/fuzzy-search";import type { Product } from "./types";
type Message = | { type: "load"; products: Product[] } | { type: "search"; query: string };
let products: Product[] = [];
self.addEventListener("message", (event: MessageEvent<Message>) => { const message = event.data;
switch (message.type) { case "load": products = message.products; break; case "search": // Return only IDs, which are cheap to clone self.postMessage(fuzzySearch(products, message.query).map((p) => p.id)); break; }});worker.postMessage({ type: "load", products: allProducts }); // Once
searchInput.addEventListener("input", (event) => { worker.postMessage({ type: "search", query: (event.target as HTMLInputElement).value, });});Even better, let the worker fetch the data itself. Then the large payload never touches the main thread at all, including the JSON parsing:
const response = await fetch("/api/products");products = await response.json(); // Parsed off the main threadGeneral rule: move the work to where the data is, and send the smallest possible result back.
Transferable Objects
Some objects can be transferred instead of copied. Transferring moves ownership of the underlying memory to the other thread in constant time, regardless of size. The sender loses access.
const buffer = new ArrayBuffer(100 * 1024 * 1024); // 100 MBconsole.log(buffer.byteLength); // 104857600
// The second argument lists objects to transfer rather than copyworker.postMessage({ buffer }, [buffer]);
console.log(buffer.byteLength); // 0, the buffer is "detached"Common transferable types include ArrayBuffer, MessagePort, ImageBitmap, OffscreenCanvas, ReadableStream, WritableStream, TransformStream, and VideoFrame.
Typed arrays like Uint8Array and Float32Array aren’t transferable themselves, but their underlying buffer is:
const pixels = new Uint8ClampedArray(width * height * 4);
// ✅ Transfer the underlying bufferworker.postMessage(pixels, [pixels.buffer]);structuredClone() accepts the same transfer list: structuredClone(value, { transfer: [buffer] }).
Use transfers whenever you’re sending large binary data, such as image pixels, audio samples, file contents, or WebAssembly memory copies, and you don’t need it on the sending side afterward.
Request/Response Patterns
The raw message API has no concept of “this response belongs to that request.” That’s fine for a fire-and-forget stream of updates, but most real code wants something that looks like an async function call.
Correlating Messages with IDs
The simplest approach is to tag each request with an ID and resolve a matching Promise when the response arrives:
type Pending = { resolve: (value: unknown) => void; reject: (reason: unknown) => void;};
export function createWorkerClient(worker: Worker) { let nextId = 0; const pending = new Map<number, Pending>();
worker.addEventListener("message", (event: MessageEvent) => { const { id, result, error } = event.data; const request = pending.get(id); if (!request) return;
pending.delete(id); if (error) { request.reject(new Error(error)); } else { request.resolve(result); } });
return function call<T>(method: string, ...args: unknown[]): Promise<T> { const id = nextId++; return new Promise<T>((resolve, reject) => { pending.set(id, { resolve: resolve as (value: unknown) => void, reject }); worker.postMessage({ id, method, args }); }); };}const methods = { fibonacci(n: number): number { return n < 2 ? n : methods.fibonacci(n - 1) + methods.fibonacci(n - 2); },};
self.addEventListener("message", (event: MessageEvent) => { const { id, method, args } = event.data;
try { const result = methods[method as keyof typeof methods]( ...(args as [number]), ); self.postMessage({ id, result }); } catch (err) { self.postMessage({ id, error: (err as Error).message }); }});const call = createWorkerClient( new Worker(new URL("./math.worker.ts", import.meta.url), { type: "module" }),);
const result = await call<number>("fibonacci", 40);This works, but you end up maintaining a small RPC framework, and the method names aren’t type-checked.
Using Comlink
Comlink is a tiny library (around 1 KB gzipped) from the Chrome team that does exactly this, with full TypeScript support. You expose an object in the worker and wrap the worker on the main thread:
import * as Comlink from "comlink";
const api = { async resize(bitmap: ImageBitmap, width: number): Promise<Blob> { const height = Math.round((bitmap.height / bitmap.width) * width); const canvas = new OffscreenCanvas(width, height); canvas.getContext("2d")!.drawImage(bitmap, 0, 0, width, height); bitmap.close(); return canvas.convertToBlob({ type: "image/webp", quality: 0.8 }); },};
export type ImageWorkerApi = typeof api;
Comlink.expose(api);import * as Comlink from "comlink";import type { ImageWorkerApi } from "./image.worker";
const imageWorker = Comlink.wrap<ImageWorkerApi>( new Worker(new URL("./image.worker.ts", import.meta.url), { type: "module" }),);
async function handleUpload(file: File) { const bitmap = await createImageBitmap(file);
// Comlink.transfer marks the bitmap as transferable instead of copied const thumbnail = await imageWorker.resize( Comlink.transfer(bitmap, [bitmap]), 400, );
preview.src = URL.createObjectURL(thumbnail);}Every method becomes async on the main thread, return types are inferred, and errors thrown in the worker reject the Promise. Comlink also supports passing callbacks with Comlink.proxy(), which is handy for progress reporting:
await worker.processFile( file, Comlink.proxy((percent: number) => { progressBar.value = percent; }),);Be careful with proxies: each call through a proxied callback is a round trip between threads, so don’t call one in a tight loop.
Error Handling and Cancellation
Uncaught errors inside a worker fire an error event on the Worker object. Without a listener, they appear in the console but your app never finds out:
worker.addEventListener("error", (event) => { console.error("Worker crashed:", event.message, event.filename, event.lineno); event.preventDefault();});
// Fires when a received message can't be deserializedworker.addEventListener("messageerror", (event) => { console.error("Could not deserialize message", event);});For request/response code, catch errors in the worker and send them back as part of the response, as in the createWorkerClient example above. That way each failing call rejects its own Promise instead of surfacing as a global error.
Cancelling work is harder. A worker processes one message at a time, so if it’s in the middle of a long synchronous loop, it won’t even see a “cancel” message until the loop ends. You have three options:
1. Ignore stale results. For search-as-you-type, this is usually enough. Track the latest request ID and drop older responses:
let latestRequest = 0;
async function search(query: string) { const requestId = ++latestRequest; const results = await searchWorker.search(query);
if (requestId !== latestRequest) return; // A newer search started renderResults(results);}2. Terminate and recreate. worker.terminate() stops the worker immediately, mid-loop. It’s the only way to truly abort synchronous work, but you lose any state the worker held and pay the startup cost again.
function cancelAndRestart() { worker.terminate(); worker = new Worker(new URL("./heavy.worker.ts", import.meta.url), { type: "module", });}3. Check a shared flag. With SharedArrayBuffer (covered below), the main thread can set a flag that the worker checks inside its loop.
Worker Pools
A single worker processes messages one at a time. If you have many independent jobs, like generating thumbnails for 200 uploaded photos, a pool of workers can run them in parallel across CPU cores.
navigator.hardwareConcurrency reports the number of logical cores. Leave at least one for the main thread:
type Job<T> = { message: unknown; transfer: Transferable[]; resolve: (value: T) => void; reject: (reason: unknown) => void;};
export class WorkerPool<T> { private idle: Worker[] = []; private queue: Job<T>[] = [];
constructor( createWorker: () => Worker, size = Math.max(1, (navigator.hardwareConcurrency ?? 4) - 1), ) { for (let i = 0; i < size; i++) { this.idle.push(createWorker()); } }
run(message: unknown, transfer: Transferable[] = []): Promise<T> { return new Promise<T>((resolve, reject) => { this.queue.push({ message, transfer, resolve, reject }); this.next(); }); }
private next() { if (this.queue.length === 0 || this.idle.length === 0) return;
const worker = this.idle.pop()!; const job = this.queue.shift()!;
const cleanup = () => { worker.removeEventListener("message", onMessage); worker.removeEventListener("error", onError); this.idle.push(worker); this.next(); };
const onMessage = (event: MessageEvent<T>) => { cleanup(); job.resolve(event.data); };
const onError = (event: ErrorEvent) => { cleanup(); job.reject(new Error(event.message)); };
worker.addEventListener("message", onMessage); worker.addEventListener("error", onError); worker.postMessage(job.message, job.transfer); }
terminate() { this.idle.forEach((worker) => worker.terminate()); this.idle = []; }}const pool = new WorkerPool<Blob>( () => new Worker(new URL("./thumbnail.worker.ts", import.meta.url), { type: "module", }),);
const thumbnails = await Promise.all( files.map(async (file) => { const bitmap = await createImageBitmap(file); return pool.run({ bitmap, width: 300 }, [bitmap]); }),);Some guidelines for pools:
- Don’t oversubscribe. More workers than cores means the OS time-slices between them, adding overhead without speeding anything up
- Mind memory. Each worker has its own JavaScript heap. Ten workers each holding a copy of a large dataset use ten times the memory
- Batch tiny jobs. If each job takes 1 ms, messaging overhead dominates. Send chunks of work instead of individual items
- Create pools lazily. Starting workers costs time and memory, so create the pool when it’s first needed, not at page load
SharedArrayBuffer and Atomics
SharedArrayBuffer gives multiple threads access to the same memory, with no copying at all. Combined with Atomics, it lets you build lock-free data structures, progress counters, and cancellation flags.
Because shared memory enables high-resolution timers that could be used for Spectre-style side-channel attacks, browsers only allow it on cross-origin isolated pages. Your HTML document must be served with these headers:
Cross-Origin-Opener-Policy: same-originCross-Origin-Embedder-Policy: require-corpYou can check at runtime with self.crossOriginIsolated. Cross-origin isolation has side effects: every cross-origin resource (images, scripts, iframes) must opt in with CORS or Cross-Origin-Resource-Policy, and popups to other origins lose their window.opener link. That can break third-party embeds, analytics, and OAuth popups, so test carefully before enabling it. Cross-Origin-Embedder-Policy: credentialless relaxes the requirement for no-credentials requests in browsers that support it.
Here’s a cancellation flag and progress counter shared between threads:
const shared = new SharedArrayBuffer(8);const control = new Int32Array(shared); // [0] = cancel flag, [1] = progress
worker.postMessage({ shared, items });
cancelButton.addEventListener("click", () => { Atomics.store(control, 0, 1); // Request cancellation});
function updateProgress() { progressBar.value = Atomics.load(control, 1); requestAnimationFrame(updateProgress);}requestAnimationFrame(updateProgress);self.addEventListener("message", (event) => { const { shared, items } = event.data; const control = new Int32Array(shared);
for (let i = 0; i < items.length; i++) { if (Atomics.load(control, 0) === 1) { self.postMessage({ cancelled: true }); return; }
processItem(items[i]); Atomics.store(control, 1, Math.round(((i + 1) / items.length) * 100)); }
self.postMessage({ done: true });});Notice that the SharedArrayBuffer is posted, not transferred. Both threads keep a reference to the same memory.
Atomics.wait() blocks a thread until another thread calls Atomics.notify(). It’s allowed in workers but not on the main thread, since blocking the main thread is exactly what we’re trying to avoid. The main thread can use the non-blocking Atomics.waitAsync() instead.
Most applications don’t need shared memory. It’s most useful for WebAssembly threads (for example, ports of C++ libraries compiled with Emscripten’s pthread support), and for real-time audio, video, and simulation code. For everything else, messages and transfers are simpler and safer.
OffscreenCanvas
Canvas rendering, especially for charts, games, and image processing, can be expensive. OffscreenCanvas lets a worker draw to a canvas without touching the DOM.
There are two ways to use it.
1. Transfer control of an on-page canvas to a worker, which then renders directly to the screen:
const canvas = document.querySelector<HTMLCanvasElement>("#chart")!;const offscreen = canvas.transferControlToOffscreen();
const worker = new Worker(new URL("./chart.worker.ts", import.meta.url), { type: "module",});worker.postMessage({ canvas: offscreen, data: chartData }, [offscreen]);self.addEventListener("message", (event) => { const { canvas, data } = event.data as { canvas: OffscreenCanvas; data: number[]; }; const ctx = canvas.getContext("2d")!;
function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); drawChart(ctx, data); requestAnimationFrame(draw); // Available in dedicated workers }
requestAnimationFrame(draw);});The chart keeps animating smoothly even when the main thread is busy with React rendering or a long task.
2. Create a standalone OffscreenCanvas in a worker for image processing, then convert the result to a Blob or ImageBitmap, as in the Comlink resize example above.
Once you transfer a canvas to a worker, the main thread can no longer draw to it, and resizing it requires sending the new dimensions to the worker. Pointer events still arrive on the main thread, so interactive canvases need to forward coordinates to the worker.
Workers with Bundlers
Modern bundlers all support the new Worker(new URL(...), { type: "module" }) pattern, which is the most portable way to write worker code:
const worker = new Worker(new URL("./parser.worker.ts", import.meta.url), { type: "module", name: "parser", // Shows up in DevTools});The bundler detects the pattern, compiles parser.worker.ts as its own entry point with its own dependency graph, emits it as a separate hashed file, and rewrites the URL.
Vite also supports a query-suffix import, which some people find more readable:
import ParserWorker from "./parser.worker.ts?worker";
const worker = new ParserWorker();This form is Vite-specific, so prefer the new URL() form in libraries or code that might move between tools.
A few configuration details are worth knowing:
- TypeScript types. Add
"WebWorker"to thelibarray in a separatetsconfigfor worker files so thatselfis typed asDedicatedWorkerGlobalScoperather thanWindow. Alternatively, declare it at the top of each worker:declare const self: DedicatedWorkerGlobalScope; - Worker format. In Vite, set
worker.format: "es"invite.config.tsif your workers use code splitting or dynamic imports, since the default is"iife" - Same-origin rule. Worker scripts must be same-origin with the page. If your assets are on a CDN subdomain, you’ll need to load the worker from your origin, or create it from a
BlobURL that imports the CDN script
In Next.js, the same new URL() pattern works in client components. Create the worker inside an effect or event handler so it never runs during server-side rendering, where Worker doesn’t exist.
Using Workers in React
Workers are long-lived resources, so tie their lifecycle to a component or create them as a module-level singleton.
A hook that creates a worker on mount and terminates it on unmount:
import { useEffect, useRef, useState } from "react";import * as Comlink from "comlink";import type { SearchWorkerApi } from "./search.worker";
export function useSearchWorker() { const workerRef = useRef<Comlink.Remote<SearchWorkerApi> | null>(null); const [ready, setReady] = useState(false);
useEffect(() => { const worker = new Worker(new URL("./search.worker.ts", import.meta.url), { type: "module", }); const api = Comlink.wrap<SearchWorkerApi>(worker); workerRef.current = api;
api.loadIndex("/api/products").then(() => setReady(true));
return () => { api[Comlink.releaseProxy](); worker.terminate(); workerRef.current = null; }; }, []);
return { search: (query: string) => workerRef.current?.search(query), ready };}function ProductSearch() { const { search, ready } = useSearchWorker(); const [query, setQuery] = useState(""); const [results, setResults] = useState<string[]>([]);
useEffect(() => { if (!ready) return;
let cancelled = false; search(query)?.then((ids) => { if (!cancelled) setResults(ids); });
return () => { cancelled = true; // Ignore stale results }; }, [query, ready]);
return ( <> <input value={query} onChange={(e) => setQuery(e.target.value)} disabled={!ready} /> <ResultsList ids={results} /> </> );}In development with Strict Mode, React mounts, unmounts, and remounts components, so this hook creates the worker twice. That’s expected, and the cleanup function terminates the first one. If worker startup is expensive, such as loading a large WebAssembly module or index, use a module-level singleton that’s created lazily on first use instead of per component.
If you’re fetching the data a worker processes, a library like TanStack Query pairs well with workers: use the worker call as the queryFn and you get caching, deduplication, and stale-result handling for free. See our TanStack Query guide for those patterns.
Workers complement React’s concurrent features rather than replacing them. useTransition and useDeferredValue keep React’s own rendering interruptible, but they can’t interrupt your synchronous computation. If the expensive part is your code rather than rendering, a worker is the right tool. Our guide to React concurrent features covers when to use each.
When Not to Use a Worker
Workers add complexity and overhead, so they aren’t always the answer:
| Situation | Better approach |
|---|---|
| Work takes under ~10 ms | Run it on the main thread; messaging overhead may exceed the work |
| The bottleneck is rendering or layout | Virtualization, CSS containment, fewer DOM nodes |
| The bottleneck is React re-renders | Memoization, React Compiler, useTransition |
| The work needs the DOM | Keep it on the main thread and yield with scheduler.yield() |
| The data is huge and can’t be transferred | Fetch and process it in the worker, or move it to the server |
| The work is network-bound | fetch is already async; a worker adds nothing |
Good candidates for workers include:
- Parsing and transforming large JSON, CSV, or XML files
- Client-side search, filtering, and sorting over large datasets
- Image, audio, and video processing
- Syntax highlighting, Markdown rendering, and code formatting for large documents
- Compression, hashing, and encryption
- Running WebAssembly modules such as SQLite, image codecs, or physics engines
- Data visualization rendering with OffscreenCanvas
Always measure first. Record a performance trace in DevTools and look for long tasks. If the long task is your code, a worker probably helps. If it’s style recalculation, layout, or React rendering, it won’t.
Debugging Workers
Chrome and Edge DevTools show each worker as a separate thread:
- Sources panel: workers appear in the threads list. You can set breakpoints in worker code just like main-thread code
- Console: a context dropdown lets you switch between the page and each worker to evaluate expressions
- Performance panel: each worker gets its own track, so you can see main-thread and worker activity side by side
- Memory panel: you can take heap snapshots of individual workers
Firefox and Safari offer similar tooling. Giving workers a name option makes them much easier to identify when you have several.
console.log inside a worker prints to the page’s console, prefixed with the worker’s context. Logged objects are snapshots, so expanding them later shows the value at log time, not the current value.
Common Pitfalls
Pitfall 1: Sending Huge Payloads on Every Message
Cloning a large object on every message can block the main thread longer than the work you offloaded. Send data once, keep it in the worker, and exchange small messages. Better still, let the worker fetch the data itself.
Pitfall 2: Using a Buffer After Transferring It
After a transfer, the original ArrayBuffer is detached and has a byteLength of 0. Reading from a typed array view over it throws or returns nothing. Only transfer data you don’t need anymore, or copy it first.
Pitfall 3: Expecting Class Instances to Survive
Structured cloning drops prototypes. A Date or Map arrives intact, but your own Money or User class arrives as a plain object without its methods. Send plain data and rehydrate it.
Pitfall 4: Forgetting to Terminate Workers
Workers keep running, and keep their memory, until you call terminate() or the page unloads. In single-page apps, workers created per component or per route leak unless you clean them up.
Pitfall 5: Creating a Worker per Task
Starting a worker means fetching and parsing its script and initializing a new JavaScript environment, which can take tens of milliseconds. Create workers once and reuse them, or use a pool.
Pitfall 6: Assuming Workers Are Free on Low-End Devices
Many budget phones have few fast cores. On those devices, a worker still frees the main thread, but the work itself may take longer than on your development laptop. Test on real low-end hardware.
Pitfall 7: Silent Failures
Without an error listener, a crashed worker just stops responding and your Promises never resolve. Add error and messageerror listeners, and consider timeouts for important requests.
Best Practices
✅ Practice 1: Profile Before You Offload
Use the DevTools Performance panel to confirm that the long task is your JavaScript, not rendering. Workers only help with the former.
✅ Practice 2: Keep the Data Where the Work Happens
Load, parse, and hold large datasets inside the worker. The main thread should send queries and receive small results.
✅ Practice 3: Transfer Binary Data
Use transfer lists for ArrayBuffer, ImageBitmap, OffscreenCanvas, and streams. Transfers take constant time regardless of size.
✅ Practice 4: Give Workers a Typed, Promise-Based API
Use Comlink or a small RPC wrapper so worker calls look like async functions. Export the API type from the worker and import it with import type on the main thread.
✅ Practice 5: Manage Lifecycles Explicitly
Create workers lazily, reuse them, and terminate them when they’re no longer needed. Tie them to component lifecycles or use module-level singletons.
✅ Practice 6: Handle Errors and Stale Results
Listen for error and messageerror, send errors back as part of responses, and drop results from requests that have been superseded.
✅ Practice 7: Treat Shared Memory as a Specialized Tool
Reach for SharedArrayBuffer only when you need it, such as WebAssembly threads or real-time data, and budget time to roll out cross-origin isolation safely.
Conclusion
Web Workers are one of the most effective tools for keeping a web app responsive. They don’t make your code faster, but they take it out of the path of user input and rendering, which is what users actually feel.
Key Takeaways:
- The main thread handles input, rendering, and your JavaScript. Long tasks over 50 ms hurt INP and make the UI feel frozen
- Module workers created with
new Worker(new URL(...), { type: "module" })work with every modern bundler postMessageuses structured cloning, which copies data and drops prototypes. Large payloads have a real cost on the sending thread- Transferable objects like
ArrayBuffer,ImageBitmap, andOffscreenCanvasmove between threads in constant time - Comlink turns workers into typed async APIs and removes most messaging boilerplate
- Cancellation requires ignoring stale results, terminating the worker, or checking a shared flag
- Worker pools parallelize independent jobs across cores. Size them to
hardwareConcurrency - 1 SharedArrayBufferenables zero-copy shared memory but requires cross-origin isolation headersOffscreenCanvasmoves canvas rendering off the main thread- Workers complement React’s concurrent features: transitions keep rendering interruptible, while workers move your own computation elsewhere
Start by recording a performance trace of your slowest interaction. If the long task is parsing, filtering, or processing data, move that one function into a worker with Comlink and measure again. It’s often the single biggest INP improvement you can make.
For more on related topics, check out our guides on the JavaScript event loop, React performance optimization, and Core Web Vitals.