Course contentsShow
← Web Development
Lesson 1992 of 2,98236. Performance Optimization TechniquesFree lesson

Moving Computation to Web Workers

Offload CPU-intensive calculations to background threads using Web Workers to keep the main thread responsive.

Moving Computation to Web Workers

You'll learn how to offload heavy computations to background threads so your UI stays smooth and responsive.

The Main Thread Bottleneck

Your browser's main thread handles everything: JavaScript execution, rendering, user interactions, and painting pixels. When you run CPU-intensive calculations—like processing large datasets, image manipulation, or complex algorithms—the main thread gets blocked. During this time, your UI freezes: buttons don't respond, animations stutter, and users get frustrated.

Web Workers: Your Parallel Processing Solution

Web Workers are separate JavaScript threads that run in the background, completely independent of the main thread. Think of them like hiring a dedicated assistant to crunch numbers in a back room while you stay free to interact with customers up front.

Workers can't access the DOM (they have no idea what a <div> is), but they're perfect for pure computation:

  • Parsing large JSON files
  • Performing complex mathematical operations
  • Processing images or video frames
  • Sorting/filtering massive arrays
  • Running algorithms that take >50ms

How It Works

You create a worker from a separate JavaScript file, send it data via messages, and receive results back—all without blocking your main thread:

// main.js
const worker = new Worker('calculator.worker.js');

worker.postMessage({ numbers: [1, 2, 3, /* ...thousands more */ ] });

worker.onmessage = (event) => {
  console.log('Result:', event.data.sum);
  // UI stays responsive during calculation!
};
// calculator.worker.js
self.onmessage = (event) => {
  const sum = event.data.numbers.reduce((a, b) => a + b, 0);
  self.postMessage({ sum });
};

Key Takeaway: Web Workers move expensive computations off the main thread into background threads, keeping your UI responsive even during intensive processing. Use them for CPU-heavy tasks that don't need DOM access.