Web Development > Web Workers

  1. Overview
  2. Cross Browser Implementation
  3. Examples

Overview

Some of the new things that are coming with HTML 5 are pretty cool. One of them is Web Workers which are designed to allow the browser to spawn a background task which runs JavaScript in parallel with the main page. This allows you to do some serious number crunching in the background without freezing the interface.

The basics of web workers are really quite simple. If you have some JavaScript in an external file, you can create a new worker that will run this JavaScript on a separate thread to the UI, you simply do

var oWorker = new Worker('worker_src.js');

Now that isn't much use unless you can get some information back from the worker. To do this the worker's source script has to post messages back to the worker object, this can be done simply by doing the following within the worker_src.js file

postMessage(oMessage);

The value oMessage that we send can be a string, or more usefully, a JSON object literal. The worker object will recieve this message and can be handled by doing

oWorker.onmessage = function(e)
{
    var oMessage = e.data; 
    /* process message here */ 
};

Sending messages the other way is just as straightforward, all we do is call the postMessage method on the worker object, again passing some JSON object literal as the message, as follows

oWorker.postMessage(oMessage);

and handle the message in the worker source file by simply including something like

onmessage = function(e)
{
    var oMessage = e.data; 
    /* process message here */
};

That's all very straightforward, but it's not much use if you can't use it across all the browsers, so what we need is some way of emulating the web worker functionality in those browsers that don't yet support it. Let's see how...