HTML 5 Web Workers

Source

HTML 5 Web Workers handle concurrency in web applications. This means that scripts can run in the background without blocking the UI, thus leaving users to continue to interact with the web page while the script works behind the scenes. The former powerhouse of web concurrency was the XmlHttpRequest which could execute a script by passing the URL of the script to the method which would process the task at the server level and then return the resulting value to the client.

Other techniques was to use the setTimeout(), setInterval() methods to initiate timers to let the script execute in peace. The new Web Worker API that is part of the HTML 5 specification eliminates these bottlenecks and is easy to implement if the browser supports it. In this tutorial, I will review the Web Worker API and provide some examples on its use.

Refer yourself to the table below to see which browser and version is currently supporting this new API.

Current Supported by Browser Version

Browser
Version
Shared Web Workers
Dedicated Web Workers
Chrome
23
YES
YES
Safari
5.1
YES
YES
Internet Explorer
9
NO
NO
Opera
12
YES
YES
Opera Mini
7
NO
NO
iOS Safari
6
YES
YES
Android Chrome
2.1
NO
NO
BlackBerry Browser
7
YES
YES

Initial Web Worker Browser Support

Browser
Shared Web Workers
Dedicated Web Workers
Chrome
22
22
Safari
5.1
5.1
Internet Explorer
10
10
Opera
12
12
Opera Mini
 
 
iOS Safari
5
5
Android Chrome
2.1
2.1
BlackBerry Browser
7
7

WebWorker Specs

WebWorkers are part of the Javascript API in HTML5. The Web Worker API runs within the web app’s sandbox and have limited scope , meaning that they cannot access different parts of a host’s computer. WebWorkers are designed to interface with resources running on a corporate server or cloud like a web service or again from the a web api. They - WebWorkers- are background tasks that doesn’t freeze up a web page where an application or some other content is running.

A simple Web Worker

Creating Web Workers is very simple. For example the following code creates a Web Worker for the process.js JavaScript file that resides on the server.

var myWW = new WebWorker(‘process.js’);

To return some data at the end of WebWorker process, you can use the postMessage which posts message back to the calling web page.

myWW.onmessage = function(event){

document.getElementById('showData').textContent = event.data;

}

The process.js file can include any JavaScript code that is needed to process whatever transaction that is needed as the following example shows:

postMessage('hello world');

SharedWorker

Another type of Web Worker is the SharedWorker. A Web Worker is considered “Shared” when many threads are using the same Web Worker. These threads can be on the same page, from a parent and inline page or different pages. ShareWorkers must implement the portMessage using the port attribute of the SharedWorker. To use the SharedWorker object you will need to implement an AddEventListener with a callback function, either inline or not, as the following example demonstrates.

var sw = new SharedWorker(‘transaction.js’);
sw.port.addEventListener(‘process’, function(evt){

postMessage(‘Hello World ’ + evt.data);

},false);

sw.port.postmessage(‘kevin’); //this is how to pass arguments for the data parameter

Worker (Dedicated)

Dedicated workers are the second type of Web Workers that are defined in the HTML5 specification. Dedicated workers are simple workers as in the example above. Dedicated workers run a single thread on a single page. Like SharedWorkers, DedicatedWorkers act on data through a messaging mechanism. You pass data as arguments, if needed, to the web worker which is a Javascript script stored in a file on the server. The worker returns data in a form of a message at the end of the process. This message can a simple confirmation, an error message, or some data that was fetched from a database or some other process.

You can’t call other server running processes directly as a Web Worker. Meaning you can’t call a php script or a python script or a server running Java Servlet or a .Net process. Web Workers are strictly Javascript based. However, the web worker can call an external process running on the server since the XmlHttpRequest is supported.

Attributes, Timers, Events and Methods

Attributes

WorkerNavigator

The WorkerNavigator is the Javascript Navigator attribute which is the user agent of the end user.

WorkerLocation
The WorkerLocation is the full path of the url, including port, host, hostname, search, pathname and hash.

WorkerGlobalScope
This is the self or this object that defines the scope of the calling object.

Timers
setTimeout and clearTimeout, setInterval() and clearInterval()
These are the standard timers that are supported by the HTML DOM.

Events
Web Workers have two standard events: onmessage and onerror

Methods
postMessage
The postMessage as we have seen manages the communication between the calling page(s) and the Web Worker.

importScripts
The importScripts is a mechanism to permit the addition of multiple external scripts to be added to the main web worker. The importScripts method is a comma delimited string as follows:

importScripts(‘test1.js’, ‘test2.js’, ‘test3.js’);

close
The close method terminates the web worker.

Detecting Web Browser Support

Since not all browser versions support web workers, you will need a way to gracefully handle the detection the available support of the web worker by the browser. You can check to see if the worker object is supported. The DOM will return the undefined message if the object is not supported which you can then try a XmlHttpRequest instead.

Here is a possible implementation example:

var worker = new Worker(‘test.js’);
if(typeof(worker)=="undefined")
{

//try calling calling an XmlHttpRequest instead

}
else
{
// manage any post messages to and from the server or worker.
}

Web workers are a great addition to the HTML specification and will provide a lot of heavy lifting that was previously handled by an assortment of different techniques and will provide a smoother user experience for web applications.

More by this Author


Comments 2 comments

Frank 3 years ago

I think you'll find that Dedicated Web Workers are supported on Chrome for Android. However, it isn't supported by the stock Android browser.


klanguedoc profile image

klanguedoc 3 years ago from Canada Author

Thanks for the info. Is Chrome supported on Android now? I think when I wrote this, I was playing around with the default browser.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working