Web Worker
A web worker runs JavaScript in a background browser agent so CPU-heavy work can avoid blocking a page's main event loop.
Download Markdown (.md)Soroush’s Product Wiki · https://wiki.soroush.uk/topic/web-worker/
01What it means
A web worker is a browser execution context that runs a script separately from a document's main agent. Dedicated workers communicate with their creator through messages, while shared workers can communicate with multiple same-origin contexts. Workers lack direct DOM access and use a different set of APIs; service workers are a specialized event-driven worker category with a distinct lifecycle.[1][2]
02Why it matters
Moving substantial computation away from the main thread can preserve input and rendering responsiveness. The boundary also forces explicit messaging and data ownership, with startup, transfer, memory, and coordination costs.
03When to use it
Use a worker for measurable CPU-heavy parsing, image processing, search, simulation, or other independent computation. Keep small or DOM-dependent work on the main thread when messaging overhead and complexity would exceed the responsiveness benefit.
04How it works
- Create a dedicated or shared worker from a script URL or module.
- Send inputs through messages, transferring ownership of large transferable objects where appropriate.
- The worker processes tasks in its own global scope and event loop without accessing the DOM.
- It posts results, progress, or errors back to the page.
- The application handles cancellation, stale results, failures, and worker termination.
05A practical example
A photo editor moves image decoding and filter calculations into a dedicated worker. It transfers pixel buffers instead of copying them, tags requests so stale results are ignored, and leaves the main thread available for pointer input.
06Where it breaks
Workers do not make algorithms faster automatically, cannot manipulate the DOM directly, and add startup and communication overhead. Structured cloning can copy large data, shared memory requires stronger isolation, and too many workers compete for device resources.
Common mistakes
- Moving trivial work to a worker without measuring messaging overhead.
- Sending large objects repeatedly instead of considering transferable data.
- Expecting a worker to read or update DOM elements.
- Applying late worker results after the user has changed or cancelled the task.
07Sources
- Web Workers APIMDN Web Docs · Official technical documentationWeb Workers API
- HTML Standard: Web WorkersWHATWG · Living web standardHTML Standard: Web Workers