Skip to content
Tutorials

Web Workers for Heavy JavaScript: Transfers, Comlink and OffscreenCanvas

AIDToolStack EditorialNovember 7, 20267 min read
JavaScriptWeb WorkersPerformanceComlink
Share:Twitter

The user drops a large CSV onto your page, you parse and aggregate it in a click handler, and for the next few seconds nothing on the page responds. No hover states, no scroll, the spinner you added doesn't even spin, because the thread that would draw it is busy. That's the case a Web Worker exists for: CPU-heavy JavaScript that can run without touching the DOM.

Workers don't make code faster. They move it off the thread that handles input and paint. This post covers when that's worth doing, how data gets across (the part that decides whether a worker helps or hurts), and the small library that makes the API bearable. Every example here ran in Chrome 152 (the Comlink ones with Comlink 4.4.2 loaded from unpkg), and the output shown is what came back.

When a worker helps, and when it doesn't

web.dev's guide to long tasks defines the threshold: "Any task that takes longer than 50 milliseconds is a long task." Long tasks are what make Interaction to Next Paint bad, which our Core Web Vitals explainer covers in detail. The same article notes that JavaScript runs on the main thread "with the exception of web workers and similar APIs."

Timeline diagram: without a worker, one long compute task on the main thread blocks a click; with a worker, the main thread posts a message, keeps handling clicks and paints, and renders the result when the worker posts it back
Timeline diagram: without a worker, one long compute task on the main thread blocks a click; with a worker, the main thread posts a message, keeps handling clicks and paints, and renders the result when the worker posts it back
SituationWorker?Why
Parsing or transforming big files, image processing, search indexing, compressionYesPure CPU work with a clear input and output
Slow fetch or database callsNoAlready asynchronous; the main thread isn't blocked while waiting
Slow rendering, layout, huge DOMNoWorkers can't touch the DOM
Lots of tiny calculations per frameUsually noMessage round-trips cost more than the work
A long loop you can splitMaybeYielding with scheduler.yield() or setTimeout may be enough

If your slow path is React re-rendering, start with our React performance guide instead; a worker can't help with rendering.

A minimal module worker

// sum.worker.js
self.onmessage = (event) => {
  const values = new Float64Array(event.data.buffer);
  let sum = 0;
  for (let i = 0; i < values.length; i++) sum += values[i];
  self.postMessage({ sum, length: values.length });
};
// main.js
const worker = new Worker(new URL("./sum.worker.js", import.meta.url), { type: "module" });
worker.onmessage = (event) => console.log(event.data);
worker.onerror = (event) => console.error("worker failed:", event.message);

The new URL(..., import.meta.url) form is what bundlers detect. Vite's docs call it "the recommended way to create workers" and warn that detection "will only work if the new URL() constructor is used directly inside the new Worker() declaration", with static option values. Our bundlers overview has the wider picture. Module workers (type: "module", so you can use import) arrived in Chrome 80, Safari 15 and Firefox 114, per MDN's compat data.

Not to be confused with service workers, which sit between your page and the network; our Manifest V3 extensions post deals with those.

What crosses the boundary: copies, by default

MDN is blunt: "Data passed between the main page and workers is copied, not shared." The copy uses the structured clone algorithm, which handles Map, Set, Date, typed arrays, Blob and friends, and refuses a few things. What I got back from Chrome 152:

worker.postMessage({ fn: () => 1 });
// DataCloneError: Failed to execute 'postMessage' on 'Worker': () => 1 could not be cloned.

structuredClone({ el: document.body });
// DataCloneError: ... HTMLBodyElement object could not be cloned.

class Point { constructor(x) { this.x = x; } get double() { return this.x * 2; } }
const p = structuredClone(new Point(2));
p instanceof Point; // false
p.double;           // undefined, it's a plain { x: 2 } now

The class one causes the quiet bugs. MDN: "The prototype chain is not walked or duplicated", and getters aren't copied either. Send plain data and rebuild objects on the other side.

Transfer big buffers instead of copying them

For large binary data, copying is the expensive part. Transferable objects move ownership instead: a "zero-copy operation" after which the sender can't use the object. You list what to transfer in the second argument:

const data = new Float64Array(1_000_000).map((_, i) => i);
console.log(data.byteLength);              // 8000000

worker.postMessage({ buffer: data.buffer }, [data.buffer]);
console.log(data.byteLength);              // 0

new Float64Array(data.buffer);
// TypeError: Cannot perform Construct on a detached ArrayBuffer

The worker summed it and replied { sum: 499999500000, length: 1000000 }.

Diagram comparing copy and transfer of an 8 MB ArrayBuffer: with copy, main and worker each hold 8 MB; with transfer, the worker holds the same 8 MB and the main thread's buffer is detached with byteLength 0
Diagram comparing copy and transfer of an 8 MB ArrayBuffer: with copy, main and worker each hold 8 MB; with transfer, the worker holds the same 8 MB and the main thread's buffer is detached with byteLength 0

Three details the short examples skip:

  • Typed arrays aren't transferable; their buffers are. Pass [view.buffer], not [view].
  • A detached view doesn't always throw. MDN says any read or write of the original "will throw". In Chrome 152, writing data[0] = 1 on the detached array did nothing and reading it gave undefined; only creating a new view threw. Either way, the data is gone from the sender. Don't keep references around.
  • structuredClone takes the same option: structuredClone(obj, { transfer: [obj.buffer] }) moves rather than copies. It's in Chrome 98, Firefox 94, Safari 15.4 and Node 17 according to the compat data.

If you need two threads reading the same memory at once, that's SharedArrayBuffer, and it comes with a hosting requirement: MDN says your document must be in a secure context and cross-origin isolated (the COOP and COEP headers), otherwise postMessage throws for it. Check crossOriginIsolated before relying on it.

Raw postMessage turns into a hand-rolled RPC protocol fast: request IDs, a switch on message type, error forwarding. Comlink from Google Chrome Labs does that with ES Proxies. Its README lists the size as about 1.2 kB gzipped. The latest release is v4.4.2 from November 2024, and the last commit on the main branch is from June 2025. The repo isn't archived. For a library this small, slow maintenance doesn't worry me much.

// worker.js
import * as Comlink from "comlink";
const api = {
  sum(buffer) {
    let s = 0;
    for (const x of new Float64Array(buffer)) s += x;
    return s;
  },
  fib(n) { return n < 2 ? n : api.fib(n - 1) + api.fib(n - 2); },
};
Comlink.expose(api);
// main.js
import * as Comlink from "comlink";
const worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
const api = Comlink.wrap(worker);

await api.fib(30);  // 832040
const data = new Float64Array(1000).map((_, i) => i);
await api.sum(Comlink.transfer(data.buffer, [data.buffer])); // 499500
data.byteLength;    // 0

api[Comlink.releaseProxy]();
worker.terminate();

Every call returns a promise, even for synchronous functions, because it's a message round-trip underneath. Comlink.transfer marks values to move instead of copy; Comlink.proxy passes callbacks by reference, which is handy for progress reporting. releaseProxy detaches the proxy from the message channel when you're done.

OffscreenCanvas: draw from the worker

Canvas-heavy work (charts with many points, image filters, games) can move entirely into a worker. You hand over control of a <canvas> once:

const canvas = document.querySelector("canvas");
const offscreen = canvas.transferControlToOffscreen();
worker.postMessage({ canvas: offscreen }, [offscreen]);
// in the worker
self.onmessage = ({ data }) => {
  const ctx = data.canvas.getContext("2d");
  ctx.fillStyle = "#2563eb";
  ctx.fillRect(0, 0, data.canvas.width, data.canvas.height);
};

After the transfer, the main thread can't draw on it: getContext("2d") threw InvalidStateError: ... Cannot get context from a canvas that has transferred its control to offscreen. Compat data lists transferControlToOffscreen in Chrome 69, Firefox 105 and Safari 16.4, with WebGL contexts on OffscreenCanvas in Safari 17. Running models in the browser is a related case; our WebGPU LLM post covers libraries that already do their heavy lifting off the main thread.

Errors, cleanup and pool size

  • An uncaught exception in the worker fires error on the Worker object. In my test, null.x inside the worker arrived as event.message = "Uncaught TypeError: Cannot read properties of null (reading 'x')". Call event.preventDefault() once you've handled it.
  • worker.terminate() kills the thread; MDN's wording is that it "is killed immediately". Whatever the worker was halfway through is abandoned, so save anything you need before calling it.
  • Spinning up a worker isn't free. Create it once and reuse it, or keep a small pool sized from navigator.hardwareConcurrency (8 on the machine I tested; yours will differ), minus one for the main thread.
  • Sub-workers must be same-origin with the parent page.

A decision checklist

  1. Profile first. Is there a long task over 50 ms, and is it your JavaScript rather than layout or rendering?
  2. Can the work run with only data in and data out, no DOM?
  3. Is the input big? Transfer ArrayBuffers instead of copying, and send plain objects, not class instances.
  4. More than two or three message types? Use Comlink rather than inventing a protocol.
  5. Drawing a lot? Move the canvas with transferControlToOffscreen.
  6. Create workers once, handle error, and terminate() them when the feature unmounts.
AE

Written by AIDToolStack Editorial

Researched from official documentation, specifications and vendor pages, listed under Sources below. Last checked November 2026.

Sources

  1. web.dev/articles/optimize-long-tasks
  2. developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers
  3. developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
  4. developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Transferable_objects
  5. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer
  6. vite.dev/guide/features#web-workers
  7. github.com/mdn/browser-compat-data/blob/main/api/Worker.json
  8. github.com/mdn/browser-compat-data/blob/main/api/_globals/structuredClone.json
  9. github.com/mdn/browser-compat-data/blob/main/api/OffscreenCanvas.json
  10. github.com/mdn/browser-compat-data/blob/main/api/HTMLCanvasElement.json
  11. github.com/GoogleChromeLabs/comlink
  12. github.com/GoogleChromeLabs/comlink/releases

Related Posts

Explore on AIDToolStack

Discover tools and servers featured in our directory.

MCP Servers

Trigger.dev Jobs MCP ServerManage Trigger.dev background jobs from your AI coding assistant. Monitor job runs, trigger tasks manually, inspect execution logs, manage schedules, and debug failed runs. The server provides operational visibility into your background job infrastructure — see which tasks are running, queued, or failed, and take action. Your AI can help diagnose job failures from execution logs, retry failed tasks, and optimize concurrency configurations for better throughput.Tailscale Network MCP ServerManage your Tailscale mesh VPN network from your AI coding assistant. View connected devices, manage ACLs, configure exit nodes, check device status, and manage DNS settings. The server provides visibility into your Tailscale network — see which machines are online, troubleshoot connectivity issues, manage network access policies, and configure routes. Useful for developers managing distributed infrastructure where Tailscale provides secure networking between services.Portainer Docker MCP ServerManage Docker environments through Portainer's API from your AI coding assistant. Control containers, images, networks, and volumes across multiple Docker hosts and Kubernetes clusters. The server provides tools for container lifecycle management, image pulling and building, stack deployment, and resource monitoring. Portainer's multi-environment management makes this server particularly valuable for teams managing containers across development, staging, and production environments.

Reviews

Sign in to leave a review.

No reviews yet. Be the first!

Comments

Sign in to leave a comment.

No comments yet. Be the first!

Sponsor Our Newsletter

Reach thousands of developers who are actively evaluating AI tools, MCP servers, and dev infrastructure. Our weekly newsletter goes to engaged technical decision-makers.

Growing subscriber baseHigh open rates

All sponsored content is clearly labeled per our editorial policy.