Web Worker
A browser API that runs heavy JavaScript computations on a separate background thread so the UI main thread stays responsive at 60fps
Table of Contents
Structure Diagram
UI & Heavy Compute Compete
- Animation & ScrollFreezes during heavy loops
- INP ResponsivenessClicks delayed by Long Tasks
- DOM AccessDirect DOM access
Separate Thread · postMessage
- Animation & ScrollSmooth 60fps UI while computing
- INP ResponsivenessMain thread stays free for input
- DOM AccessNo DOM (communicate via messages)
What is Web Worker?
A browser API that runs heavy JavaScript computations on a separate background thread so the UI main thread stays responsive at 60fps. It is a core concept in Performance & Optimization within Web Dev.
Core Principles
Because browser JavaScript shares a single main thread with layout, painting, and user input, CPU-heavy work like large JSON parsing, image processing, or encryption freezes the interface.
A Web Worker spawns an isolated background thread that runs JavaScript in parallel. Workers have no direct access to window or the DOM—avoiding shared-memory race conditions—and exchange data with the main thread via postMessage / onmessage.
Practical Takeaways
- Avoid serialization bottlenecks with Transferable Objects: Cloning multi-megabyte
ArrayBufferpayloads can negate worker gains. Pass[buffer]as the transfer list for zero-copy ownership transfer. - Offload genuinely heavy tasks: Spawning a worker and marshaling messages has overhead. Target tasks exceeding ~50ms such as compression, syntax parsing, cryptography, or WebAssembly execution.
- Simplify messaging with RPC wrappers: Libraries like
Comlinklet you call worker methods with normalasync/awaitsyntax instead of hand-writing message switchboards.
Notable Examples
- In-browser image/video editors and PDF tools: Run filters,
OffscreenCanvasrendering, and Wasm encoders in workers so sliders and previews stay at 60fps. - Web IDEs (VS Code for the Web / Monaco): Execute language servers, TypeScript type-checking, and full-text search indexing off the main thread.