Monday, March 8, 2010

Simple worker example in HTML5


I just added an example of workers to the HTML5 detection and examples code on which I talked about in my two previous posts. Workers are, undoubtedly, the most interesting feature of the HTML5 specs. A lot of the specifications derive from the work done by the Google gears team. Kudos for finally bringing multi-threaded applications to the web!!!

Here's a statement on web workers in the current specifications:

This specification defines an API that allows Web application authors to spawn background workers running scripts in parallel to their main page. This allows for thread-like operation with message-passing as the coordination mechanism.

It also has the following statement:

Workers are relatively heavy-weight, and are not intended to be used in large numbers. Generally, workers are expected to be long-loved, have a high start-up cost, and a high per-instance memory cost.

Example initialization: (in parent page)
var worker = new Worker("worker.js");
worker.onmessage = function(){}

In worker.js:
postMessage();//used to send a message back to the "parent" thread.

Currently, most browsers support just strings being passed as messages, although the developers working with the W3C are also trying to get it into the specifications to pass around generic objects.

There are also some stipulations on what can be done within a worker thread:
  1. Workers have no access to the DOM
  2. Workers do not have direct access to the 'parent' page.
The first point above means that one cannot do any DOM manipulations within the worker thread. i.e. no access to document, window, document.body or any of the DOM elements.

The second stipulation means that the worker thread can communicate with only it's parent thread, and cannot call any functions or use any variables on the "parent" page that initialized it.

The demo I have put together works quite well in Chrome 4 and Safari 4. The demo works quite weirdly in FF 3.5, but only for the "terminate" call, where it seems to terminate the worker thread after a random period of time after I click the "Stop" button. However, that might be due to Firebug or any other extensions I may have installed. Do let me know in case you experience otherwise.

Here is the zip file once more:


No comments: