JavaScript is single-threaded — there's only one chef in the kitchen. If the chef spends 5 minutes chopping vegetables, no orders get taken, no food gets served, and customers (users) wait. Web Workers are like hiring a prep cook — you hand off the chopping (postMessage), and the chef keeps taking orders while the prep cook does the heavy lifting. When the prep cook is done, they hand the vegetables back (onmessage), and the chef plates the dish.
This article covers dedicated workers, postMessage, and transferables.
Prerequisites: Async #1 — The Event Loop
1. The Problem — Main Thread Blocking
Loading editor...
2. Creating a Worker — Move Work Off the Main Thread
Loading editor...
3. Transferable Objects — Zero-Copy Data Transfer
Transferables transfer ownership to the worker — the main thread loses access:
Loading editor...
4. Worker Types Comparison
Loading editor...
5. Worker Limitations
Loading editor...
Key Takeaways
- Workers run on a separate thread — no shared scope, no DOM access.
- Communication is via
postMessage— structured clone (copy) by default. - Use transferable objects (
ArrayBuffer,MessagePort) for zero-copy — the sender loses access. - Dedicated Workers = one page. Shared Workers = multiple pages/tabs. Service Workers = network proxy.
- Workers are ideal for: heavy computation, image processing, parsing large files, cryptographic operations.
- Always call
worker.terminate()when done to free resources.
Next: Web APIs #3 — Intersection Observer — lazy load images and infinite scroll without scroll handlers.
