Web Workers in HTML5

What are Web Workers?

Web Workers API is being developed currently. The Web Workers are background workers that run scripts in parallel to their main page. The Web Worker itself is independent of any user interface scripts. They allow thread-like operations on the client side that include message-passing mechanism for coordination or data retrieval. If you expected to have a long-lived process, to have a high start-up performance cost, and a high per-instance memory cost Web Workers can be a good solution.

How to use Web Workers API?

The specification for Web Workers specify two kinds of workers – Dedicated Workers and Shared Workers. The first kind wraps a given task and perform it. The second can have multiple connections and uses ports for posting messages.
The first thing to do in order to use the Web Workers API is to create the worker and pass it an execution script URL. Here is an example for how to do that with Dedicated Workers:
var worker = new Worker('worker.js');
In Shared Web Workers you will create a SharedWorker object instead of Worker object: 
var worker = new SharedWorker('worker.js');
When you create a Web Worker it exposes the following events which help the main page to communicate with the worker:
  • onerror – signals that an error occurred in the worker
  • onmessage – enables to receive worker messages back in the main page. Those messages are raised by the postMessage inner worker event
Also, the worker exposes the following inner functions:
  • terminate – stops the worker’s execution
  • postMessage – posts a message for the listeners of the onmessage event in the main page
In Shared Web Workers you have an addition inner event – onconnect and also the port object.

Check whether your browser supports the web workers or not:



if(typeof(Worker)!=="undefined")
{
        // Yes! Web worker support!
        // Some code.....
}
else
{
        // Sorry! No Web Worker support..
}

Example:

Now, let's create our web worker in an external JavaScript.
Here we create a script that counts. The script is stored in the "CountWorker.js" file:



CountWorker.js:
var i=0;
function timedCount()
{
           i=i+1;
          postMessage(i);
          setTimeout("timedCount()",500);
}

timedCount();

HTML File:

<!DOCTYPE html>

<html>
<body>

<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button> 
<button onclick="stopWorker()">Stop Worker</button>
<br><br>

<script>
    var w;

    function startWorker() {
        if (typeof (Worker) !== "undefined") {
            if (typeof (w) == "undefined") {
                w = new Worker("Countworkers.js");
            }
            w.onmessage = function (event) {
                document.getElementById("result").innerHTML = event.data;
            };
        }
        else {
            document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Workers...";
        }
    }

    function stopWorker() {
        w.terminate();
    }
</script>

</body>
</html>

Explanation:
Now that we have the web worker file, we need to call it from an HTML page. The following lines of code checks if the worker already exists, if not, it creates a new web worker object and runs the code in "CountWorker.js":

if (typeof(w)=="undefined")
{
           w=new Worker("demo_workers.js");
}

Then we can send and receive messages from the web worker. Add an "onmessage" event listener to the web worker.

w.onmessage=function(event){
                         document.getElementById("result").innerHTML=event.data;
                     };

To terminate a web worker, and free browser/computer resources, use the terminate() method.

w.terminate();


Web Workers API enables the creation of background scripts which can communicate with the main page. This ability is very powerful and can help web developers to create more responsive UI and to achieve things that couldn’t be achieved in web applications in the past. Currently Web Workers are only a draft but there are browsers that support them currently such as Chrome, FireFox and Opera.

NOTE: We could not access the DOM Object within Web Workder. Here is a very good diagram summarinzing that:




Some Scenarios for Web Workers

It’s true that the limitations we’ve seen above on the resources available inside Web Workers narrow down the number of interesting scenarios. Still, if you just take some time to think about it, you’ll start to see new interesting usages:
  • image processing by using the data extracted from the <canvas> or the <video> elements. You can divide the image into several zones and push them to the different Workers that will work in parallel. You’ll then benefit from the new generation of multi-cores CPUs. The more you have, the faster you’ll go.
  • big amount of data retrieved that you need to parse after an XMLHTTPRequest call. If the time needed to process this data is important, you’d better do it in background inside a Web Worker to avoid freezing the UI Thread. You’ll then keep a reactive application.
  • background text analysis: as we have potentially more CPU time available when using the Web Workers, we can now think about new scenarios in JavaScript. For instance, we could imagine parsing in real-time what the user is currently typing without impacting the UI experience. Think about an application like Word (of our Office Web Apps suite) leveraging such possibility: background search in dictionaries to help the user while typing, automatic correction, etc.
  • concurrent requests against a local database. IndexDB will allow what the Local Storage can’t offer us: a thread-safe storage environment for our Web Workers.

But in a general manner, as long as you don’t need the DOM, any time-consuming JavaScript code that may impact the user experience is a good candidate for the Web Workers. However, you need to pay attention to 3 points while using the Workers:
  1. The initializing time and the communication time with the worker shouldn’t be superior to the processing itself
  2. The memory cost of using several Workers
  3. The dependency of the code blocks between them as you may then need some synchronization logic. Parallelization is not something easy.


Get more detail on Web Workers here

Happy Programming... :)


Comments

Popular posts from this blog

Data Bound Controls in ASP.Net - Part 4 (FormView and DetailsView controls)

ASP.net: HttpHandlers

The Clickjacking attack and X-Frame-Options