Web Workers

7 out of 11 rated this helpful - Rate this topic

Note  See the section titled Updates to Web Workers in IE10 Platform Preview 4 to learn about updates to this feature.

Internet Explorer 10 and Windows Store apps using JavaScript introduce support for Web Workers. The Web Workers API defines a way to run scripts in the background. Web Workers are specified in the World Wide Web Consortium (W3C)'s Web Workers specification, which is currently in the Working Draft stage.

Traditionally, browsers have been single-threaded, forcing all the script in your application to run together in a single UI thread. Although you can create the illusion of several things happening at the same time by using Document Object Model (DOM) events and the setTimeout API, it takes only one computationally intensive task to bring the user experience to a screeching halt.

The Web Worker API provides a way for web application authors to spawn background scripts that run in parallel with the main page. You can spawn several threads at a time to use for long-running tasks. A new worker object requires a .js file, which is included via an asynchronous request to the server.


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

All communication to and from the worker thread is managed through messages. Both the host worker and the worker script can send messages by using postMessage and listen for a response by using the onmessage event. The content of the message is sent as the data property of the event.

The following example creates a worker thread and listens for a message.


var hello = new Worker('hello.js');
hello.onmessage = function(e) {
  alert(e.data);
};

The worker thread sends the message to be displayed.


postMessage('Hello world!');

Two-way communication with Web Workers

To set up two-way communication, both the main page and the worker thread listen for the onmessage event. In the following example, the worker thread returns the message after a specified delay.

First, the script creates the worker thread.


var echo = new Worker('echo.js'); 
echo.onmessage = function(e) {
  alert(e.data); 
}

The message text and timeout values are specified in a form. When the user clicks the submit button, the script passes two pieces of information to the worker in a JavaScript object literal. To prevent the page from submitting the form values in a new HTTP request, the event handler also calls preventDefault on the event object. Note that you cannot send references to DOM objects to a worker thread. Web Workers are limited in what data they can access. Only JavaScript primitives such as Object or String values are allowed.


<script>
window.onload = function() {
  var echoForm = document.getElementById('echoForm'); 
  echoForm.addEventListener('submit', function(e) {
    echo.postMessage({
      message : e.target.message.value,
      timeout : e.target.timeout.value
    }); 
    e.preventDefault();
  }, false); 
  }
</script>
<form id="echoForm">
  <p>Echo the following message after a delay.</p>
  <input type="text" name="message" value="Input message here."/><br/>
  <input type="number" name="timeout" max="10" value="2"/> seconds.<br/>
  <button type="submit">Send Message</button>
</form>


Finally, the worker listens for the message and returns it after the specified timeout interval.


onmessage = function(e) 
{
  setTimeout(function() 
  {
    postMessage(e.data.message);
  }, 
  e.data.timeout * 1000);
}

In Internet Explorer 10 and Windows Store apps using JavaScript, the Web Workers API supports the following methods.

MethodDescription

voidclose();

Terminates the worker thread.

voidimportScripts(inDOMString... urls);

Imports a comma-separated list of additional JavaScript files.

voidpostMessage(in any data);

Sends a message to or from the worker thread.

 

Internet Explorer 10 and Windows Store apps using JavaScript support the following Web Workers API attributes:

AttributeTypeDescription
locationWorkerLocationRepresents an absolute URL, including protocol, host, port, hostname, pathname, search, and hash components.
navigatorWorkerNavigatorRepresents the identity and onLine state of the user agent client.
selfWorkerGlobalScopeThe worker scope, which includes the WorkerLocation and WorkerNavigator objects.

 

Internet Explorer 10 and Windows Store apps using JavaScript support the following Web Workers API events:

EventDescription

onerror

A runtime error occurred.

onmessage

Message data received.

 

WindowTimers

The Web Workers API also supports the updated HTML5 WindowTimers functionality.

MethodDescription

void clearInterval(inlonghandle);

Cancels a timeout identified by handle.

void clearTimeout(inlonghandle);

Cancels a timeout identified by handle.

long setInterval(inanyhandler, inoptionalanytimeout, inany... args);

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(inanyhandler, in optional any timeout, in any... args);

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 clearTimeout.

 

For hands-on demonstrations of Web Workers in action, see Web Worker Fountains and Web Worker Harness for test262 on the IE Test Drive.

Updates to Web Workers in IE10 Platform Preview Build 4

Internet Explorer 10 Platform Preview Build 4 imposes a limit of 25 Web Worker threads per process. You can create more workers in script, but only 25 will be active at the same time.

Creating a worker will not throw an exception if the maximum number of threads is reached. The call always succeeds, and you can add handlers and post messages to it. However, the worker might not start until one of the existing 25 threads is available.


// Coding pattern before PPB4
try {
    var worker = new Worker(url);
} catch(ex) {
    // IE might throw...?
}

// After PPB4
var worker = new Worker(url);
// Continue with confidence...

Related topics

HTML5
Internet Explorer 10 Guide for Developers

 

 

Build date: 4/8/2013

Did you find this helpful?
(1500 characters remaining)

Community Additions

ADD
© 2013 Microsoft. All rights reserved.