Back to APIs

Web Workers

Concurrency

An API that enables executing JavaScript in background threads. The worker thread can perform tasks without interfering with the user interface.

SupportGlobal 99%+
BaselineWidely available
ImpactHigh
Popularity🔥 75

When to Use

  • Parsing or manipulating massive JSON datasets.
  • Client-side image processing, video encoding, or audio manipulation.
  • Complex mathematical calculations (e.g. cryptography, physics engines).
  • Formatting large rich-text documents.

When NOT to Use

  • When the task involves manipulating the DOM directly.
  • When the overhead of serializing/deserializing data via postMessage exceeds the cost of just running the task on the main thread.
  • For simple UI state updates.

Code Examples

Offloading Heavy Processing

The heavyCalculation function completely freezes the worker thread, but the main thread remains untouched. The UI remains perfectly responsive.

// main.js
const worker = new Worker('worker.js');
worker.postMessage({ type: 'PROCESS_DATA', payload: massiveArray });

worker.onmessage = (e) => {
  console.log('Processed data received:', e.data);
};

// worker.js
self.onmessage = (e) => {
  if (e.data.type === 'PROCESS_DATA') {
    const result = heavyCalculation(e.data.payload);
    self.postMessage(result);
  }
};

Advantages

  • Keeps the Main Thread completely free, ensuring 60fps animations and immediate user interaction regardless of workload.
  • Supports fetching resources via XMLHttpRequest or fetch natively.
  • Can utilize multi-core processors effectively in the browser.

Limitations

  • Absolutely zero access to the DOM or the window object.
  • Data passed between the main thread and workers must be copied (Structured Clone Algorithm), which can be slow for massive objects unless using Transferable Objects.
  • Harder to debug and coordinate state across threads.

Common Mistakes

  • Passing massive nested objects back and forth via postMessage, causing serialization bottlenecks on the main thread.
  • Spinning up dozens of workers. Workers are heavy OS-level threads; usually, a small pool matching the CPU core count is optimal.
  • Failing to call worker.terminate() when the worker is no longer needed, causing memory leaks.

References