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.