Thursday, March 28, 2024

Introduction to HTML5 Web Workers: Browser Support, Non-accessible Elements and Error Handling

written by David Rousset

In the first part of this article, we introduced HTML5 Web Workers, and showed you how you can use the technology to post messages using JSON. This week we will tell you which web browsers support them, discuss the elements that are non-accessible to them, and dig into error handling & debugging.

Browsers Support Image 1

Web Workers have just arrived in the IE10 Platform Preview. This is also supported by Firefox (since 3.6), Safari (since 4.0), Chrome & Opera 11. However, this is not supported by the mobile versions of these browsers. If you’d like to have a more detailed support matrix, have a look here: http://caniuse.com/#search=worker

In order to dynamically know that this feature is supported in your code, please use the feature detection mechanism. (You shouldn’t use some user-agent sniffing!)

To help you, there are 2 available solutions. The first one is to simply test the feature yourself using this very simple piece of code:

/* Checking if Web Workers are supported by the browser */

if (window.Worker) {

// Code using the Web Workers

}

The second one is to use the famous Modernizr library (now natively shipped with the ASP.NET MVC3 project templates). Then, simply use a code like that:

<script type=”text/javascript”>

var divWebWorker = document.getElementById(“webWorkers”);

if (Modernizr.webworkers) {

divWebWorker.innerHTML = “Web Workers ARE supported”;

}

else {

divWebWorker.innerHTML = “Web Workers ARE NOT supported”;

}

</script>

Here, for instance, is the current support in your browser: Web Workers are not supported inside your browser.

This will allow you to expose 2 versions of your application. If Web Workers are not supported, you will simply execute your JavaScript code as usual. If Web Workers are supported, you will be able to push some of the JavaScript code to the workers to enhance the performance of your applications for the most recent browsers. You won’t then break anything or build a specific version only for the very latest browsers. It will work for all browsers with some performance differences.

Non-accessible Elements From a Worker

Rather than looking at what you don’t have access to from Workers, let’s take a look at what you only have access to:

Method

Description

void close();

Terminates the worker thread.

void importScripts(urls);

A comma-separated list of additional JavaScript files.

void postMessage(data);

Sends a message to or from the worker thread.

 

Attributes

Type

Description

location

WorkerLocation

Represents an absolute URL, including protocol, host, port, hostname, pathname, search, and hash components.

navigator

WorkerNavigator

Represents the identity and onLine state of the user agent client.

self

WorkerGlobalScope

The worker scope, which includes the WorkerLocation and WorkerNavigator objects.

 

Event

Description

onerror

A runtime error occurred.

onmessage

Message data received.

 

Method

Description

void clearInterval(handle);

Cancels a timeout identified by handle.

void clearTimeout(handle);

Cancels a timeout identified by handle.

long setInterval(handler, timeout value, arguments);

Schedules a timeout to be run repeatedly after the specified number of milliseconds. Note that you can now pass additional arguments directly to the handler. If handler is a DOMString, it is compiled as JavaScript. Returns a handle to the timeout. Clear with clearInterval.

long setTimeout(handler, timeout value, arguments);

Schedules a timeout to run after the specified number of milliseconds. Note that you can now pass additional arguments directly to the handler. If handler is a DOMString, it is compiled as JavaScript. Returns a handle to the timeout. Clear with clearTimeou


Note:
This table is extracted from our MSDN documentation: HTML5 Web Worker

In summary, you don’t have access to the DOM. Here is a very good diagram summarizing that:

Image 2

For instance, since you don’t have access to the window object from a worker, you won’t be able to access the Local Storage (which doesn’t seem to be thread-safe anyway). Those limitations may look too constraint for developers used to multi-threaded operations in other environments. However, the big advantage is we won’t fall into the same problems we usually encounter: lock, races conditions, etc. We won’t have to think about that with Web Workers. This makes the Web Workers something very accessible, while allowing some interesting performance boosts in specific scenarios.

Error Handling & Debugging

It is very easy to handle errors raised from your Web Workers. You simply have to subscribe to the OnError event in the same way we’ve done it with the OnMessage event:

myWorker.addEventListener(“error”, function (event) {

_output.textContent = event.data;

}, false);

This is the best Web Workers can give you natively to help you debugging their code… This is very limited, isn’t it?

The F12 Development Bar for a Better Debugging Experience

To go beyond that, IE10 offers you to directly debug the code of your Web Workers inside its script debugger like any other script.

For that, you need to launch the development bar via the F12 key and navigate to the “Script” tab. You shouldn’t see the JS file associated to your worker yet. But right after pressing the “Start debugging” button, it should magically be displayed:

Image 3

Next step is to simply debug your worker like you’re used to debugging your classic JavaScript code!

Image 4

IE10 is currently the only browser offering you that. If you want to know more about this feature, you can read this detailed article: Debugging Web Workers in IE10

An Interesting Solution to Mimic console.log()

At last, you need to know that the console object is not available within a worker. Thus, if you need to trace what’s going on inside the worker via the .log() method, it won’t work as the console object won’t be defined. Hopefully, I’ve found an interesting sample that mimics the console.log() behavior by using the MessageChannel: console.log() for Web Workers. This works well inside IE10, Chrome & Opera but not in Firefox as it doesn’t support the MessageChannel yet.

Note: In order to make the sample from this link work in IE10, you need to change this line of code:

console.log.apply(console, args); // Pass the args to the real log

By this one:

console.log(args); // Pass the args to the real log

Then, you should be able to obtain such results:

Image 5

DEMO: If you want to try this console.log() simulation, navigate here -> http://david.blob.core.windows.net/html5/HelloWebWorkersJSONdebug.htm <-

This article was reprinted with permission from Microsoft Corporation. This site does business with Microsoft Corporation.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured