Over a million developers have joined DZone.

Web Workers in HTML5

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

Do these application demands sound familiar?

  • 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)]
[System.ComponentModel.ToolboxItem(false)]  
[ScriptService]
public class EchoService : WebService
{
  [WebMethod]
  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) {
                    postMessage(xhr.responseText);
                }
            }
        };
        xhr.send(params);
    } catch (e) {
        postMessage('Error occured');
    }
}
 
function callWSMethod() {
    getData("http://localhost:30051/WebWorkers/EchoService.asmx/Echo?msg=Hello", "msg=Hello");
}
 
callWSMethod();

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:

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

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:

WebWorkerResult

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.

Summary

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.

 

Source: http://blogs.microsoft.co.il/blogs/gilf/archive/2011/04/08/web-workers-in-html5.aspx

 

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}