Partager via


Web Workers

Internet Explorer 10 and Windows 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.

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 apps using JavaScript, the Web Workers API supports the following methods.

Method Description

void close();

Terminates the worker thread.

void importScripts(inDOMString... urls);

Imports a comma-separated list of additional JavaScript files.

void postMessage(in any data);

Sends a message to or from the worker thread.

 

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

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

 

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

Event Description

onerror

A runtime error occurred.

onmessage

Message data received.

 

WindowTimers

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

Method Description

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.

 

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 IE10 Platform Preview Build 4
try {
    var worker = new Worker(url);
} catch(ex) {
    // IE might throw...?
}

// After IE10 Platform Preview Build 4
var worker = new Worker(url);
// Continue with confidence...

API Reference

Web Workers

Samples and tutorials

Web Workers sample

How to explore the Mandelbrot set using HTML5

Internet Explorer Test Drive demos

Mandelbrot Explorer

The Web Worker Fountains

Web Worker Harness for test262

IEBlog posts

Debugging Web Workers in IE10

Web Workers in IE10: Background JavaScript Makes Web Apps Faster

Specification

Web Workers

HTML5 Threading with Web Workers and Data Storage with IndexedDB

Introduction to HTML5 Web Workers: The JavaScript Multi-threading Approach