Web Workers: Dedicated Thread Creation, Message Queues & Memory Isolation
- Last updated
- Prerequisites:
- JavaScript single-threaded event loop
- DOM vs WorkerGlobalScope
- browser
- web-workers
- threads
- concurrency
- postmessage
- main-thread
Read at your depth
The practical view
Web Workers let you run heavy JavaScript computations on background OS threads without blocking the main UI thread. Created via `const worker = new Worker('worker.js')`. Communication happens through asynchronous message passing via `worker.postMessage()` and `onmessage`. Workers do not have access to the DOM, `window`, or `document`, but can access `fetch`, `IndexedDB`, `crypto`, and `WebSockets`.
The same idea in other frameworks
`useWorker` hook or Comlink proxy offloading calculations outside render.Angular CLI Web Worker generator (`ng generate web-worker`).Vue composables wrapping Worker instances with reactive ref bindings.Svelte actions or services communicating with Workers over typed ports.Legacy vs modern
Main-Thread Blocking Canvas Processing vs Dedicated Web Worker
Processing 50MB image pixels on the main thread freezes the entire UI; offloading to a Web Worker keeps the page interactive.
const processed = applyHeavyFilters(imageData); // ❌ Freezes UI for 2 secondsworker.postMessage({ buffer }, [buffer]); // ✅ NEW: Off-main-thread zero-copyInterview gotchas
Context
Tests understanding of thread-safety and environment boundaries in the browser.
The mechanical answer
No. Web Workers cannot access the DOM (`document`, `window`), nor can they access synchronous `localStorage` (which is thread-unsafe). Allowing multi-threaded access to DOM tree pointers without locks would cause race conditions and memory corruption. However, Workers *can* render to a canvas via `OffscreenCanvas` and use asynchronous storage via `IndexedDB`.
Trap
Do not say that Workers have no storage access at all. They have full access to `IndexedDB`, `CacheStorage`, and the Origin Private File System (OPFS).
Context
Checks architecture scaling and thread pool management knowledge.
The mechanical answer
Creating a Web Worker is relatively heavy: it spawns an OS thread and boots an independent V8 Isolate, taking ~20-50ms and consuming several megabytes of RAM. In high-throughput applications, spawning a new Worker per task is an anti-pattern. Instead, use a **Worker Pool** (a fixed set of pre-warmed workers matching `navigator.hardwareConcurrency`) with a task queue to distribute jobs.
Trap
Spawning hundreds of concurrent Workers will exhaust system threads and crash the browser tab.