HTML Web Workers

Imagine you’re the chef of a busy restaurant. Up until now, you've been preparing every dish by yourself, but the kitchen just received a new appliance — a food processor (our Web Worker). This machine can independently handle tasks like chopping vegetables or kneading dough, allowing you to focus on other things like grilling the steak to perfection. This is essentially what Web Workers do for web pages; they allow complex tasks to run in the background, without interrupting the main flow of the script that makes your website interactive and engaging.

Why Use Web Workers?

When you visit a website, your browser executes scripts to make the page interactive. However, some scripts are like making a multi-course meal single-handedly; they're complex and can take a while to complete. If the browser tries to execute these scripts all at once, it might temporarily become unresponsive. This is not a great user experience.

Enter Web Workers: they let the browser outsource some of these heavy-lifting tasks. Just like delegating tasks in a kitchen allows you to prepare meals faster and more efficiently, Web Workers help keep websites responsive by running scripts in the background.

Basic Example of a Web Worker

Step 1: Check for Support

First, we should ensure the user's browser supports Web Workers. Not every kitchen is equipped with our fancy food processor, after all.

if (window.Worker) {
  // Web Workers are supported.
  // You can start using them!
} else {
  // Web Workers are not supported.
  // Consider a different approach.
}

Step 2: Creating a Web Worker

Let's say we have a task (a script) we want to run in the background — for example, a complex calculation that counts to a billion. Instead of doing this in our main script and potentially freezing our website, we'll delegate this task to a Web Worker.

We need two files to make this happen: the main script (perhaps main.js) that runs on our page and a separate script (worker.js) that will be run by the Worker.

  • In main.js: This is like deciding to use the food processor and turning it on.
// Check for support
if (window.Worker) {
  // Create a new Web Worker
  const myWorker = new Worker('worker.js');
 
  myWorker.onmessage = function(e) {
    console.log('Message received from worker', e.data);
  };
 
  // Start the worker with a message
  myWorker.postMessage('start');
}
  • In worker.js: This is the recipe or task you're giving the food processor to handle on its own.
onmessage = function(e) {  
  if (e.data === 'start') {
    let count = 0;
    for (let i = 0; i < 1000000000; i++) {
      count += i;
    }
    postMessage(count);
  }
};

Step 3: Communication Between Your Page and the Worker

Notice how in main.js, we sent a message to start the Worker. The Worker then received this message, ran a heavy calculation, and sent back the result. The communication between your main script and the Worker is done through messages using postMessage() and responding to onmessage events. It's like if you could send a recipe card to the food processor and get a notification back when the meal is ready.

Final Thoughts

Web Workers can significantly enhance the performance and responsiveness of web applications by handling complex operations in the background. Just remember, Workers run independently and can't directly access the DOM or some of the window's objects and methods. Their communication is purely through messages, keeping the main thread free to ensure a smooth and responsive user interface.

This is just the beginning of what you can do with Web Workers! With this foundation, you can start exploring more complex interactions and see how they can improve your web applications.