JavaScript / Programmings / Technologies

An Introduction to Web Workers

Overview

Browsers use single thread for JavaScript and UI. So synchronous JavaScript calls will block this thread, thus rendering will be blocked. For example, if our website needs to do UI events, fetch and process large amount of API data and manipulate DOM. It is not possible do all these simultaneously since the script execution happens within a single thread, in browsers.

For example run the below script in your browser console, you will get a warning about unresponsive script.


    function expensiveLoop(){
       for (var i = 0; i <= 1000000000; i += 1){
          var j = i;
       }
       alert("Completed " + j + "iterations" );
    }
    expensiveLoop();

HTML5 gives us some solution for this, Web Workers!

Web Workers allow web content to running scripts in background threads, without interrupting User Interface. Also a Web Worker can perform I/O using XMLHttpRequest. Communication between worker and parent page (main thread) is done via Passing Messages, Web Workers specification defines an API for this.

You can run JavaScript code inside the worker thread, with some exceptions. For example, you can’t directly manipulate the DOM from inside a worker, or use some default methods and properties of the window object. But you can use a large number of items available under window, including WebSockets, and data storage mechanisms like IndexedDB.

Getting Started

Web Workers run in background in isolated thread, means they don’t share the same JavaScript global execution context as the main page’s JavaScript. The only way they can interact with the page’s main (UI) JavaScript is by sending and receiving messages. As isolated thread,the code that execute needs to be contained in a separate file. Before we do that, create a new Worker object in main page. The constructor takes the name of the worker script,


    var worker = new Worker('task.js');

where task.js is a JavaScript file contains the script to execute.

If the file specified exists, browser will create a worker thread, worker asynchronously download the script, if file not found, returns 404 and fails silently. The worker begins only after downloading and executing the script file specified.

After creating the worker, start it by calling the postMessage() method,


    worker.postMessage(); // Start the worker.

postMessage() can accept either a string or JSON object as its single argument.
Message passed by Web Worker is accessed using onmessage event in the main page

The JavaScript expensive script which make UI unresponsive earlier, on executing in main thread, can be execute with Web Worker in background in parallel without making UI unresponsive.It is rewritten as follows,
In the Main Page,



    var worker = new Worker('expensiveLoop.js');
         
    worker.onmessage = function (event) {
      alert("Completed " + event.data + "iterations" );
    };
         
    worker.onerror = function (event) {
      console.log(event.message, event);
    };

Following is the content of expensiveLoop.js file. This makes use of postMessage() API to pass the communication back to main page


    for (var i = 0; i <= 1000000000; i += 1){
       var j = i;
    }
    postMessage(j);

Web Workers don’t stop by themselves but the page that started them can stop them by calling terminate() method.

    worker.terminate();

It is only an Introduction, If you are interested to know more about Web Workers, hopefully you can find it in the following References.

References
———–
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers
https://html.spec.whatwg.org/multipage/workers.html
http://www.html5rocks.com/en/tutorials/workers/basics/
http://www.tutorialspoint.com/html5/html5_web_workers.htm

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s