It’s Festive Season! Enjoy 30% Off

Use code FESTIVE30 at checkout

Code has been added to clipboard!

How and When to Use HTML5 Web Workers?

Reading time 2 min
Published Feb 27, 2019
Updated Oct 1, 2019

TL;DR – Web workers are JavaScript codes running in the background without disturbing web page performance.

Web Workers Explained

Using web workers in HTML5 allows you to prevent the execution of bigger tasks from freezing up your web page. A web worker performs the job in the background, independent of other scripts and thus not affecting their performance. The process is also called threading, i.e., separating the tasks into multiple parallel threads. During the time, the user can browse normally, as the page stays fully responsive.

In the example below, you can see a simple script for a web worker made for counting numbers:

Example
var i=0;

function timedCount() {
    i=i+1;
    postMessage(i);
    setTimeout("timedCount()", 500);
}

timedCount();

The script contains a postMessage() method which allows posting a message (i.e., the numbers) to an HTML document. However, web workers are not usually used from such simple tasks as they wouldn't use a lot of CPU power and disturb website performance anyway.

A Full Web Worker Code

The code for web workers in HTML5 has to be stored in an external JavaScript file. However, for them to work properly, you also have to include some code in your HTML document:

Example
<!DOCTYPE html>
<html>
<body>

<p>Count numbers: <output id="res"></output></p>
<button onclick="startCounting()">Start Counting</button> 
<button onclick="stopWorker()">Stop Counting</button>

<p><strong>Note:</strong>All Internet Explorer versions before 9, do not support the Web Workers.</p>

<script>
 var l;
 
function startCounting() {
  console.log("Worker started");
  if(typeof(Worker) !== "undefined") {
    if(typeof(l) == "undefined") {
      l = new Worker("demo_workers.js");
    }
    l.onmessage = function(event) {
      document.getElementById("res").innerHTML = event.data;
    };
  } else {
    document.getElementById("res").innerHTML = "Browser does not support Workers";
  }
}
 
function stopWorker() { 
  console.log("Worker terminated");
  l.terminate();
  l = undefined;
}
</script>

</body>
</html>

We'll explain the most crucial parts of the code in the table below.

Code section Meaning
var l;
function startCounting() {
Sets up a global variable
if(typeof(l) == "undefined") {
l = new Worker("demo_workers.js");
}
Initializes a web worker
l.onmessage = function(event) {
document.getElementById("res").innerHTML = event.data;
};
Allows listening to messages and updating the page accordingly
} else {
document.getElementById("res").innerHTML = "Browser does not support Workers";
}
}
Informs the user if their browser doesn't support web workers
function stopWorker() {
console.log("Worker terminated");
l.terminate();
l = undefined;
}
Terminates the web worker

Web Workers: Useful Tips

  • By using setInterval() and setTimeout() JavaScript functions, you can make web workers perform periodic tasks.
  • You cannot access DOM elements using web workers, so don't include any in their scripts.
  • Not sure when to use web workers? The most common tasks include spell checking, syntax highlighting, prefetching and caching data.

Browser support

Browser image
Chrome
4+
Browser image
Edge
All
Browser image
Firefox
3.5+
Browser image
IE
10+
Browser image
Opera
10.6+
Browser image
Safari
4+

Mobile browser support

Browser image
Chrome
18+
Browser image
Firefox
4+
Browser image
Opera
11+
Browser image
Safari
5.1+