H

HTML Handbook

Clean • Professional

HTML Web Workers API

3 minute

HTML Web Workers API

The Web Workers API allows JavaScript to run in the background without blocking the main page.

Normally, JavaScript runs on a single thread (the main thread). If a heavy task is running (like a large loop), it can freeze the UI. Web Workers solve this problem by moving such tasks to a background thread, keeping the web page smooth and responsive.

Example:

Without Web Workers, if you run a loop with millions of iterations, your webpage may hang. With Web Workers, the loop runs in the background, and the user can still scroll or click buttons smoothly.

How Web Workers Work

  • The main thread handles the UI (clicks, inputs, rendering).
  • A Web Worker runs in the background.
  • Communication happens through messages (postMessage and onmessage).

This means:

  • The worker does not block the UI.
  • Both main thread and worker can send/receive data asynchronously.

Types of Web Workers

  1. Dedicated Workers
    • Used by a single script/page.
    • Best for page-specific background tasks.
  2. Shared Workers
    • Can be shared between multiple scripts or browser tabs.
    • Example: multiple tabs accessing the same chat server.
  3. Service Workers (brief mention)
    • More advanced.
    • Used for offline support, push notifications, caching.
    • Example: Progressive Web Apps (PWA).

Creating a Web Worker

A Web Worker needs a separate JavaScript file.

Example:

main.js

// Create a new worker
let worker = new Worker("worker.js");

// Send message to worker
worker.postMessage("Start the calculation");

// Receive message from worker
worker.onmessage = function(event) {
  console.log("Result from worker: " + event.data);
};

worker.js

// Worker code (runs in background)
onmessage = function(event) {
  console.log("Worker received: " + event.data);

  let sum = 0;
  for (let i = 0; i < 1000000000; i++) {
    sum += i;
  }

  // Send result back
  postMessage(sum);
};

Communication Between Main Script and Worker

  • postMessage() → send data.
  • onmessage → receive data.

Example: Sending and receiving a message

// main.js
worker.postMessage("Hello Worker!");

// worker.js
onmessage = function(e) {
  postMessage("Hello Main Script, I got your message: " + e.data);
};

Terminating a Web Worker

Workers keep running in the background until you manually stop them.

  • From the main script:
worker.terminate();
  • Workers also auto-terminate when the browser tab is closed.

Error Handling in Web Workers

Errors inside workers don’t crash the main thread. You can catch them using onerror.

Example:

worker.onerror = function(e) {
  console.log("Error in worker: " + e.message);
};

Limitations of Web Workers

  • Cannot access the DOM directly (document, window, etc. are not available).
  • Limited access to certain APIs.
  • Communication is only via messages (not direct variable sharing).
  • Each worker uses memory and CPU – don’t create too many unnecessarily.

Browser Support for Web Workers

  • Supported in all modern browsers: Chrome, Firefox, Edge, Safari, Opera.
  • Not supported in very old browsers (like IE 9 and below).

Always check compatibility before using:

if (window.Worker) {
   console.log("Web Workers are supported!");
} else {
   console.log("Sorry, your browser doesn't support Web Workers.");
}

 

Article 0 of 0