Click here to Skip to main content
15,881,882 members
Articles / Programming Languages / Javascript

Web Workers in HTML5

Rate me:
Please Sign up or sign in to vote.
4.27/5 (3 votes)
8 Apr 2011CPOL4 min read 22.4K   5   1
In this post, I’m going to explain the Web Workers API and show you how you can use it today with most of the major browsers (not including IE9).

Web Workers in HTML5

Introduction

Do these application demands sound familiar:

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

If you are working in the 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 the web environment, this is 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 show you how you can use it today with most of the major browsers (not including IE9).

What are Web Workers?

The 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 a 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 the 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 performs it. The second can have multiple connections and uses ports for posting messages.

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

In Shared Web Workers, you will create a SharedWorker object instead of the Worker object:

JavaScript
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. These 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. Now that we have understood a little bit about what Web Workers are and their API, let's 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 echoes the data it receives, and its implementation looks like:

C#
[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, let's look at the worker.js file:

C#
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 calls the first function with some test data. The last piece of code is the main page itself:

HTML
<!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 wired to the onmessage event. The handler inserts the data returned by the postMessage function (that exists inside 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 about how to take this API to the next level in order to do more interesting things.

Summary

Let's 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 is 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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead sparXys
Israel Israel
Gil Fink is a web development expert and ASP.Net/IIS Microsoft MVP. He is the founder and owner of sparXys. He is currently consulting for various enterprises and companies, where he helps to develop Web and RIA-based solutions. He conducts lectures and workshops for individuals and enterprises who want to specialize in infrastructure and web development. He is also co-author of several Microsoft Official Courses (MOCs) and training kits, co-author of "Pro Single Page Application Development" book (Apress) and the founder of Front-End.IL Meetup. You can read his publications at his website: http://www.gilfink.net

Comments and Discussions

 
QuestionPlz help me Pin
waxsantu24-Sep-12 18:33
waxsantu24-Sep-12 18:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.