← Lessons

quiz vs the machine

Platinum1820

Frontend

Web Workers Offloading

Running heavy JavaScript off the main thread to keep UI smooth.

6 min read · advanced · beat Platinum to climb

Why offload

All rendering and most JavaScript share the main thread. A heavy computation there blocks input, animation, and paint. A Web Worker runs script on a separate thread so the main thread stays free.

How communication works

  • The main thread and worker do not share normal variables. They exchange data by postMessage, which copies the payload using structured cloning.
  • Each side listens for the message event and responds.
  • A worker has no DOM access; it cannot touch the page directly and instead returns results for the main thread to render.

Avoiding copy cost

Large buffers can be expensive to clone. You can transfer an ArrayBuffer instead, handing ownership to the worker so no copy is made. The sender loses access after transfer.

Good candidates

  • Parsing or transforming large data sets.
  • Image processing, compression, and cryptography.
  • Anything CPU bound that would otherwise drop frames.

Tradeoffs

  • Messaging has overhead, so very tiny tasks are not worth offloading.
  • Debugging across threads is harder, and workers add startup cost.

Key idea

Web Workers run CPU heavy JavaScript on a separate thread, communicating by message passing, so the main thread keeps rendering smoothly.

Check yourself

Answer to earn rating on the learn ladder.

1. How do a worker and the main thread share data by default?

2. What does a Web Worker NOT have access to?

3. Why transfer an ArrayBuffer instead of copying it?