HTML5 Web Workers


A web worker is a JavaScript running in the background, without affecting the performance of the page.


  • While executing scripts on an HTML page, if the page becomes unresponsive before completing the script, a web worker runs the JavaScript in the background without affecting the performance of the page and runs the scripts independently.
  • While the web worker is running in the background you can continue doing whatever you want like clicking, selecting etc.
  • Web workers are heavy weight and are not used in large numbers.
  • They do not have direct access to the web page and DOM API.
  • Web workers cannot block the browser UI but they can consume the CPU cycles and make the system less responsive.

Working of Web Workers

  • They are always initialized with the URL of a JavaScript file which will have the code that the worker will be executing.

  • Syntax:
    var worker= new Worker ('example.js');

  • If any javascript file exists a new worker thread will be spawned by the browser which will be downloaded asynchronously. If error 404 is returned the worker will fail.
  • If there are multiple javascript files, they can be imported by using the importScripts() method.

  • Syntax for importScripts() method:
    importScripts(“name.js”, “example.js”);

  • postMessage() method helps in communicating between the web worker and its parent page. This method accepts either a string or JSON object as a single argument depending on the browser.
  • The onmessage event accesses the message that is passed on by the web worker.
  • The web workers cannot stop on their own. They have to be stopped by calling the terminate() method.

  • Syntax:

  • A web worker that is terminated does not respond to the messages or perform any additional computations. A worker can never be restarted instead a new one can be created by using the same URL.

Example : Demonstrating a Web worker for counting numbers

Step 1: Create a JavaScript file with a name 'demowebwork.js' and save it with the following script

var a = 0;
function timedCount()
     a = a + 1;

Step 2: Create an HTML file and save the following code

<!DOCTYPE html>

          <p>The count is: </output></p>
               var worker = new Worker('demowebwork.js');
               worker.onmessage = function (event)
                     document.getElementById('result').textContent =;

The count is: 3

Note: The number in the above output keeps on changing every second.