Dedicated Web Workers provide a simple means for web content to run scripts in background threads. Once created, a worker can send messages to the spawning task by posting messages to an event handler specified by the creator. However, they work within a global context different from the current window (using the window shortcut instead of self in order to get the current global scope within a Worker will return, in fact, an error).

The worker thread can perform tasks without interfering with the user interface. In addition, they can perform I/O using XMLHttpRequest (although the responseXML and channel attributes are always null).

About thread safety

The Worker interface spawns real OS-level threads, and concurrency can cause interesting effects in your code if you aren't careful. However, in the case of web workers, the carefully controlled communication points with other threads means that it's actually very hard to cause concurrency problems. There's no access to non-thread safe components or the DOM and you have to pass specific data in and out of a thread through serialized objects. So you have to work really hard to cause problems in your code.

Spawning a worker

Creating a new worker is simple. All you need to do is call the Worker() constructor, specifying the URI of a script to execute in the worker thread, and, if you wish to be able to receive notifications from the worker, set the worker's Worker.onmessage property to an appropriate event handler function.

Line 1 in this example creates a new worker thread. Line 3 sets up a listener to handle message events from the worker. This event handler will be called when the worker calls its own Worker.postMessage() function. Finally, Line 7 starts the worker thread.

Note : The URI passed as parameter of the Worker constructor must obey the same-origin policy . There is currently disagreement among browsers vendors on what URIs are of the same-origin; Gecko 10.0 (Firefox 10.0 / Thunderbird 10.0 / SeaMonkey 2.7) and later do allow data URIs and Internet Explorer 10 does not allow Blob URIs as a valid script for workers.

Passing data

Data passed between the main page and workers are copied, not shared. Objects are serialized as they're handed to the worker, and subsequently, de-serialized on the other end. The page and worker do not share the same instance, so the end result is that a duplicate is created on each end. Most browsers implement this feature as structured cloning.

Before continuing, let's create for didactical purpose a function named emulateMessage() which will simulate the behavior of a value which is cloned and not shared during the passage from a worker to the main page or vice versa:

A value which is cloned and not shared is called message. Back to talk about workers, messages can be sent to and from the main thread by using postMessage(). The message event's data attribute contains data passed back from the worker.

Note: As usual, background threads – including workers – cannot manipulate the DOM. If actions taken by the background thread need to result in changes to the DOM, they should post messages back to their creators to do that work.

The structured cloning algorithm can accept JSON and a few things that JSON can't like circular references.

Passing data examples

Example #1: Create a generic "asynchronous eval()"

The following example shows how to use a worker in order to execute asynchronously any kind of JavaScript code through eval() within the worker:

It is a possible method to switch the content of each mainpage-worker – and vice versa – message.

Passing data by transferring ownership (transferable objects)

Google Chrome 17 and Firefox 18 contain an additional way to pass certain kind of objects (Transferable objects, that is objects implementing the Transferable interface) to or from a worker with high performance. Transferable objects are transferred from one context to another with a zero-copy operation. This means a vast performance improvement when sending large data. Think of it as pass-by-reference if you're from the C/C++ world. However, unlike pass-by-reference, the 'version' from the calling context is no longer available once transferred. Its ownership is transferred to the new context. For example, when transferring an ArrayBuffer from your main app to Worker, the original ArrayBuffer is cleared and no longer usable. Its content is (quite literally) transferred to the Worker context.

Spawning subworkers

Workers may spawn more workers if they wish. So-called subworkers must be hosted within the same origin as the parent page. Also, the URIs for subworkers are resolved relative to the parent worker's location rather than that of the owning page. This makes it easier for workers to keep track of where their dependencies are.

Embedded workers

There is not an "official" way to embed the code of a worker within a web page as for the <script> elements. But a <script> element which does not have a src attribute and has a type attribute that does not identify an executable mime-type will be considered a data block element, that JavaScript could use. "Data blocks" is a more general feature of HTML5 that can carry almost any textual data. So, a worker could be embedded in this way:

Handling errors

When a runtime error occurs in worker, its onerror event handler is called. It receives an event named error which implements the ErrorEvent interface. The event doesn't bubble and is cancelable; to prevent the default action from taking place, the worker can call the error event's preventDefault() method.

The error event has the following three fields that are of interest:

message

A human-readable error message.

filename

The name of the script file in which the error occurred.

lineno

The line number of the script file on which the error occurred.

Accessing the navigator object

Workers may access the navigator object, which is available within their scope. It contains the following strings which can be used to identify the browser, just as can be done from normal scripts:

appName

appVersion

platform

userAgent

Importing scripts and libraries

Worker threads have access to a global function, importScripts() , which lets them import scripts or libraries into their scope. It accepts as parameters zero or more URIs to resources to import; all of the following examples are valid:

The browser loads each listed script and executes it. Any global objects from each script may then be used by the worker. If the script can't be loaded, NETWORK_ERROR is thrown, and subsequent code will not be executed. Previously executed code (including code deferred using window.setTimeout()) will still be functional though. Function declarations after the importScripts() method are also kept, since these are always evaluated before the rest of the code.

Note: Scripts may be downloaded in any order, but will be executed in the order in which you pass the filenames into importScripts() . This is done synchronously; importScripts() does not return until all the scripts have been loaded and executed.

Examples

This section provides several examples of how to use DOM workers.

Performing computations in the background

One way workers are useful is to allow your code to perform processor-intensive calculations without blocking the user interface thread. In this example, a worker is used to calculate Fibonacci numbers.

The JavaScript code

The following JavaScript code is stored in the "fibonacci.js" file referenced by the HTML in the next section.

The worker sets the property onmessage to a function which will receive messages sent when the worker object's postMessage() is called. (Note that this differs from defining a global variable of that name, or defining a function with that name. var onmessage and function onmessage will define global properties with those names, but they will not register the function to receive messages sent by the web page that created the worker.) This starts the recursion, spawning new copies of itself to handle each iteration of the calculation.

The web page creates a div element with the ID result , which gets used to display the result, then spawns the worker. After spawning the worker, the onmessage handler is configured to display the results by setting the contents of the div element, and the onerror handler is set to dump the error message.