Parallel Processing

Web Workers

Unlock the power of multi-threading in web applications with Web Workers - run JavaScript in background threads without blocking the UI.

What are web workers in JavaScript?

A Web Worker runs JavaScript in a background thread so heavy work (parsing, image processing, large calculations) doesn't freeze the page. You create one with new Worker("worker.js") and communicate by passing messages with postMessage and onmessage. Workers can't access the DOM.

// main.js
const worker = new Worker("worker.js", { type: "module" });
worker.postMessage([1, 2, 3]);
worker.onmessage = (e) => console.log("sum:", e.data);

// worker.js
onmessage = (e) => postMessage(e.data.reduce((a, b) => a + b, 0));

Key Features

Non-blocking

Keep UI responsive during heavy computations

Parallel

Run multiple tasks simultaneously

Isolated

Separate execution context for safety

Interactive Web Workers Demo

Experience the power of Web Workers with prime calculations, image processing, and data sorting - all running without blocking the main UI thread.

Web Workers Architecture

Main Thread vs Worker Thread

  • Main Thread: UI, DOM manipulation, events
  • Worker Thread: Heavy computations, data processing
  • Communication: Message passing only
  • Isolation: Separate global scopes
  • No DOM Access: Workers can't access DOM directly

Worker Types

  • Dedicated Workers: One-to-one relationship
  • Shared Workers: Multiple script access
  • Service Workers: Background sync, caching
  • Worklets: Low-level, performance-critical
  • Inline Workers: Script as blob URL

Worker Creation & Communication

Creating Workers

External Script File
const worker = new Worker('worker.js');
Inline Worker (Blob)
const blob = new Blob([script], { type: 'application/javascript' }); const worker = new Worker(URL.createObjectURL(blob));

Message Passing Protocol

Main Thread → Worker
// Send message worker.postMessage({ command: 'process', data: [1, 2, 3, 4, 5] }); // Listen for response worker.addEventListener('message', (e) => { console.log(e.data); });
Worker → Main Thread
// In worker.js self.addEventListener('message', (e) => { const result = processData(e.data); // Send response back self.postMessage({ status: 'complete', result: result }); });

Transferable Objects

Transfer ownership of objects for better performance:

// Transfer ArrayBuffer ownership const buffer = new ArrayBuffer(1024); worker.postMessage(buffer, [buffer]); // After transfer, buffer is empty in main thread console.log(buffer.byteLength); // 0 // Worker receives full ownership self.addEventListener('message', (e) => { const receivedBuffer = e.data; console.log(receivedBuffer.byteLength); // 1024 });

Common Use Cases & Patterns

Heavy Computations

  • • Mathematical calculations (primes, factorials)
  • • Cryptographic operations
  • • Data analysis and statistics
  • • Complex algorithms
  • • Machine learning inference

Data Processing

  • • Large dataset sorting and filtering
  • • JSON parsing and transformation
  • • CSV/Excel file processing
  • • Text analysis and search
  • • Data validation and cleaning

Media Processing

  • • Image filters and transformations
  • • Audio processing and encoding
  • • Video frame manipulation
  • • Canvas-based animations
  • • Real-time media analysis

Network Operations

  • • Background API requests
  • • WebSocket connection management
  • • Periodic data synchronization
  • • File uploads with progress
  • • Real-time data streaming

Best Practices & Performance Tips

Worker Management

  • • Terminate workers when done
  • • Pool workers for reusability
  • • Handle worker errors gracefully
  • • Monitor memory usage
  • • Limit concurrent workers

Data Transfer Optimization

  • • Use transferable objects
  • • Minimize message size
  • • Batch multiple operations
  • • Avoid circular references
  • • Consider compression for large data

Error Handling

  • • Listen for worker errors
  • • Implement timeout mechanisms
  • • Provide fallback strategies
  • • Log errors for debugging
  • • Handle worker termination

Performance Monitoring

  • • Measure execution time
  • • Monitor CPU usage
  • • Track memory consumption
  • • Profile worker performance
  • • Compare with main thread

Advanced Features & Techniques

Worker Pool Implementation

Manage multiple workers efficiently:

class WorkerPool { constructor(scriptUrl, poolSize = 4) { this.workers = []; this.availableWorkers = []; this.tasks = []; for (let i = 0; i < poolSize; i++) { const worker = new Worker(scriptUrl); this.workers.push(worker); this.availableWorkers.push(worker); worker.addEventListener('message', (e) => { this.handleWorkerMessage(worker, e); }); } } execute(data) { return new Promise((resolve, reject) => { const task = { data, resolve, reject }; if (this.availableWorkers.length > 0) { this.assignTask(task); } else { this.tasks.push(task); } }); } }

SharedArrayBuffer (Advanced)

Shared Memory
// Create shared buffer const sharedBuffer = new SharedArrayBuffer(1024); const sharedArray = new Int32Array(sharedBuffer); // Share with worker worker.postMessage({ sharedBuffer });
Atomic Operations
// Atomic operations for thread safety Atomics.add(sharedArray, 0, 1); Atomics.compareExchange(sharedArray, 1, 0, 42); Atomics.wait(sharedArray, 2, 0);

OffscreenCanvas Integration

Render graphics in workers:

// Main thread const canvas = document.getElementById('canvas'); const offscreen = canvas.transferControlToOffscreen(); worker.postMessage({ canvas: offscreen }, [offscreen]); // Worker thread self.addEventListener('message', (e) => { const canvas = e.data.canvas; const ctx = canvas.getContext('2d'); // Render in background ctx.fillStyle = 'red'; ctx.fillRect(0, 0, 100, 100); });

Code Editor

<button id="block">Heavy loop on the main thread</button>
<button id="worker">Same loop in a Web Worker</button>
<p>Click a button, then try typing here: <input></p>
<p id="out"></p>

Preview

Web Workers — step by step

1 / 4
1

Create a Web Worker

Create a worker by passing the script URL to the Worker constructor: const worker = new Worker('worker.js'). The worker runs in its own thread with no access to the DOM, window, or document.

1 of 4
🔍Workers Cannot Access the DOM
Web Workers run in a completely isolated thread with no access to the DOM, window, document, or parent scope. They can use fetch, XMLHttpRequest, timers, and many Web APIs. This isolation is what makes them thread-safe — communication only happens via message passing.

🎯 Quick Check

Can a Web Worker directly manipulate the DOM?

Web Workers: summary

Key points

  • Messages are copied with structured cloning. Transfer ArrayBuffers to move large data without copying.
  • Workers can use fetch, timers, IndexedDB and WebSockets, but not document or window.
  • Service Workers are a different kind of worker that intercepts network requests for offline support.

Frequently asked questions

›Can a web worker access the DOM?

No. Send results back to the main thread with postMessage and update the DOM there.