Web Workers in HTML5

April 8, 2011

no comments

Web Workers in HTML5

Is these application demands sound familiar:Web Workers in HTML5

  • Using background I/O operations
  • Web services polling
  • Processing large amount of data
  • Running an algorithm in the background
  • More

If you are working in Windows environment you will probably use a background worker (or another thread) for achieving these demands in order to make your application more responsive. In web environment this was impossible since JavaScript is a single threaded environment. You couldn’t run multiple scripts simultaneously but you could make hacks by using functions like setInterval. In HTML5 a new API is currently developed in order to enable web applications to run background scripts. In this post I’m going to explain this API – Web Workers – and to show you how you can use them today with most of the major browsers (not including IE9).  

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. I won’t discuss Shared Web Workers so you can read about them in the Web Workers current draft. After we understand a little bit about  What are Web Workers and their API lets look at an example.

Web Workers Example

The following example shows how to create a Web Worker and run it in order to call a simple Echo web service.

The service echo the data it receives and its implementation looks like:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class EchoService : WebService
  public string Echo(string msg)
    return msg;

The only interesting thing here is the ScriptService attribute that enables client scripts to call the service.

Next lets look at the worker.js file:

var xhr;
function getData(url, params) {
    try {
        xhr = new XMLHttpRequest();        
        xhr.open('POST', url, false);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
    } catch (e) {
        postMessage('Error occured');
function callWSMethod() {
    getData("http://localhost:30051/WebWorkers/EchoService.asmx/Echo?msg=Hello", "msg=Hello");

In the worker’s script there are two functions. The first function (getData) is used to make the request to the service and to post messages back to the main page when the data returns from the service. The second function (callWSMethod) just call the first function with some test data.

The last piece of code is the main page itself:

    <title>Worker example: Simple Ajax Call</title>
        <output id="result">
    <script type="text/javascript">       
        var worker = new Worker('worker.js');
        worker.onmessage = function (event) {            
            document.getElementById('result').innerHTML = event.data;

As you can see the Web Worker is being created by using the worker.js file and a handler is wire to the onmessage event. The handler inserts the data returned by the postMessage function (that exists inside the worker.js) into an output element (a new HTML5 element for outputs). You can try this example on Chrome and then you’ll get the following result:


This is a very simple example and you can start thinking how to take this API to the next level in order to do more interesting things.


Lets sum up, 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. For further details about Web Workers you can read the Web Workers current draft.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>