Web Workers vs Main Thread: Offloading Heavy Work
Learn the interview-ready mental model, practical trade-offs, and production patterns for this web fundamentals topic.
Topic content
The browser main thread handles rendering, input, and JavaScript execution. Long tasks block the UI and drop frames. Web Workers run JavaScript in a separate thread, allowing heavy computation without freezing the interface. They communicate via message passing and cannot access the DOM directly.
The main thread is the head chef — it must stay focused on plating food (rendering) and taking orders (user input). Web Workers are the prep cooks in the back — they handle chopping vegetables and long tasks so the head chef never gets overwhelmed.
1Why the Main Thread Matters
It handles JS execution, DOM updates, layout, paint, and input events. Tasks longer than ~50ms are considered 'long tasks' and cause jank.
2Web Worker Basics
Workers run in isolated threads with their own event loop. Create them with `new Worker('worker.js')` and communicate using `postMessage()`.
self.onmessage = (e) => {
const result = heavyComputation(e.data);
self.postMessage(result);
};3Transferable Objects & Best Practices
Use Transferable Objects (ArrayBuffer, etc.) to avoid expensive structured cloning for large data. Keep messaging minimal and batch work.
- ✓Main thread must stay free for rendering and input
- ✓Web Workers enable background computation
- ✓Use postMessage for communication
- ✓Prefer Transferable Objects for large data
- ✓Great for parsing, image processing, crypto, ML inference
- ✓Not suitable for DOM manipulation or frequent small tasks
- ✓Measure responsiveness before and after offloading