Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 37 ยท JavaScript Performance

Web Workers: Moving Work Off the Main Thread

Use Web Workers to run heavy calculations in parallel, keep the page responsive, pass data efficiently with transferables and know when a worker is not worth it.

Chunking and yielding make a long task friendlier, but the total work still runs on the main thread. A Web Worker gives you a second thread. The worker has its own event loop, so a heavy calculation there never blocks clicks, scrolling or rendering on the page.

Typical jobs for a worker are image processing, parsing large files, searching or sorting big data sets, encryption, compression and running a game's physics. This lesson shows how to use one and how to avoid the costs that make workers slower when used badly.

How workers work

flowchart LR
  Main["Main thread<br/>UI, DOM, events"] -- "postMessage(data)" --> Worker["Worker thread<br/>heavy computation"]
  Worker -- "postMessage(result)" --> Main

The two threads share nothing by default and talk only by messages.

A worker cannot touch the DOM, window or document. It has fetch, timers, IndexedDB, crypto and many more APIs. Data you send is copied with the structured clone algorithm (unless you transfer it), so you cannot accidentally create race conditions on shared objects.

A worker in a few lines

Normally a worker lives in its own file: new Worker("worker.js"). In the sandbox here we create the worker from a string using a Blob URL, so the demo is self-contained:

Summing numbers in a worker

While the worker runs, the counter keeps ticking, which proves the main thread is free. If your browser blocks Blob workers inside the sandboxed preview, the page prints a message instead; the code is correct for real pages, where you would load worker.js from your own origin.

The cost of messages

Copying data takes time. Sending a 100 MB array to a worker and back can cost more than the calculation you wanted to offload. Three ways to reduce the cost:

  1. Send less. Send IDs or small parameters and let the worker fetch the data itself.
  2. Transfer ownership. An ArrayBuffer can be transferred instead of copied: it moves to the worker in constant time and becomes unusable in the sender.
  3. Share memory. SharedArrayBuffer lets both threads see the same bytes (it needs cross-origin isolation headers and careful use of Atomics).
JS Copy versus transfer

Press Run (or Ctrl + Enter) to see the console output here.

No output.

With worker.postMessage(buffer, [buffer]) the same thing happens across threads.

Worker patterns

  • A pool. Starting a worker costs a few milliseconds and some memory. Create a small pool (often navigator.hardwareConcurrency - 1 at most) and reuse it.
  • Request/response with ids. Add an id to each message so the main thread can match replies to promises.
  • Comlink-style wrappers. Libraries can make a worker feel like calling an async function. The idea is simple enough to write yourself.
JS Promise wrapper around messages

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Other kinds of workers

  • Service workers sit between the page and the network for caching and offline use.
  • Shared workers are shared between tabs of the same origin.
  • Worklets run small scripts inside rendering pipelines, such as audio or paint.
  • OffscreenCanvas lets a worker draw to a canvas, taking rendering work off the main thread.

When not to use a worker

  • The task takes under about 20 ms: message overhead may dominate.
  • The task needs the DOM: move only the pure computation.
  • The data is huge and cannot be transferred: measure first.
  • You can simply do less work, or do it on the server.

Always measure on a mid-range phone. A worker does not make code faster, it only makes the page more responsive.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What can a Web Worker NOT do?

    Workers have no access to document or window. They communicate with the main thread via messages.
  2. 2. What happens to an ArrayBuffer you transfer to a worker?

    Transfer moves ownership in constant time and detaches the original.
  3. 3. Why can offloading to a worker sometimes make an app slower?

    Structured cloning large data takes time; offload only when computation outweighs message cost.
  4. 4. Which statement about workers is true?

    The benefit is responsiveness, not raw speed.

Summary

  • Workers run JavaScript on another thread and talk to the page with postMessage.
  • They cannot use the DOM; keep them for pure computation and data processing.
  • Reduce message cost by sending less, transferring buffers or sharing memory.
  • Reuse a small pool of workers and match replies with ids.
  • Measure first: small tasks may not be worth the overhead.

Next: Finding and Fixing Memory Leaks