Lesson 60 +10 XP

HTML Web Workers

HTML Web Workers

Web Workers let heavy JavaScript run in the background without freezing your page. Like hiring a helper to do the slow work while you keep playing!

The problem

JavaScript normally runs on ONE line (the main thread). If it does something slow, the page freezes: buttons stop working, animations stop.

The solution: web workers

A Web Worker is JavaScript that runs in the background on its own thread. Your page stays smooth while the worker does the heavy lifting.

Create a worker file

First, create a separate JavaScript file for the worker, e.g. demo_workers.js:

// This runs in the background
var i = 0;
function timedCount() {
  i = i + 1;
  postMessage(i);  // send the result back
  setTimeout(timedCount, 1000);
}
timedCount();

Start the worker from your page

var w;

function startWorker() {
  if (typeof (Worker) !== "undefined") {
    // Start the worker from the file
    w = new Worker("demo_workers.js");

    // Listen for messages from the worker
    w.onmessage = function (event) {
      document.getElementById("result").innerHTML = event.data;
    };
  } else {
    // Old browsers don't support workers
    document.getElementById("result").innerHTML = "Sorry, no Web Worker support.";
  }
}

Stop the worker

function stopWorker() {
  w.terminate();
  w = undefined;
}

Talking between worker and page

  • Worker → page: postMessage(data)
  • Page → worker: worker.postMessage(data)
  • Page listens: worker.onmessage

Check if supported

Some older browsers don't support workers. Always check:

if (typeof (Worker) !== "undefined") {
  // Supported, go ahead!
} else {
  // Not supported, do something else
}

TL;DR

  • Web Workers run JavaScript in the background.
  • The page stays smooth while the worker works.
  • Create a worker file, then new Worker("file.js").
  • Communicate with postMessage and onmessage.
  • terminate() stops the worker.
  • Check browser support first.