HTML Web Worker API

πŸš€ Introduction to Web Workers

The Web Worker API enables running JavaScript code in background threads separate from the main UI thread. This helps keep your web app responsive by offloading heavy computations or tasks to workers. 🧠⚑

>>β€œRun heavy scripts without freezing the UI β€” Web Workers to the rescue!” πŸ¦Έβ€β™‚οΈ

πŸ“Œ What Are Web Workers?

Web Workers are JavaScript files that run in parallel to your main script, without blocking user interactions like clicks or scrolling. Communication happens via message passing.

βš™οΈ Creating a Basic Web Worker

Step 1: Create a worker script (worker.js):

worker.js

self.onmessage = function(event) {
  const num = event.data;
  // Perform a CPU-heavy task (e.g. Fibonacci)
  function fibonacci(n) {
    return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);
  }
  const result = fibonacci(num);
  self.postMessage(result);
};

Step 2: Use the worker in your main script:

Main script

const worker = new Worker('worker.js');

worker.postMessage(40); // Send data to worker

worker.onmessage = function(event) {
  console.log('Fibonacci result:', event.data);
  worker.terminate(); // Stop worker when done
};

worker.onerror = function(error) {
  console.error('Worker error:', error.message);
};

🧠 Communication Between Main Thread and Worker

  • Main thread sends messages with worker.postMessage(data).
  • Worker receives messages via onmessage event handler.
  • Worker sends results back with postMessage().
  • Main thread listens for results with worker.onmessage.

πŸ’‘ Use Cases for Web Workers

  • Complex calculations (math, data processing).
  • Image or video processing.
  • Fetching and parsing large data asynchronously.
  • Real-time data visualization and games.

⚠️ Important Notes

  • Workers run in isolated contexts β€” they can’t access DOM directly.
  • Use worker.terminate() to stop workers and free resources.
  • Transferable objects can be used to optimize data transfer between threads.
  • Workers have limited access to browser APIs for security reasons.

πŸ”— Useful Resources

>>β€œWeb Workers help build fast, smooth, and responsive web apps by harnessing parallelism.” ⚑