Under The Hood
frontend browser HTML Web Workers / DedicatedWorkerGlobalScope

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

react equivalent
`useWorker` hook or Comlink proxy offloading calculations outside render.

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.

before → after
Main Thread Freezing Loop
const processed = applyHeavyFilters(imageData); // ❌ Freezes UI for 2 seconds
Web Worker Offload
worker.postMessage({ buffer }, [buffer]); // ✅ NEW: Off-main-thread zero-copy

Interview 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).

Under The Hood — a multi-depth technical interview hub.

Third-party licenses Press ⌘ K to search.