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.

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

See Worker for reference documentation on workers; this article complements that one by offering examples and added details. For a list of functions available to workers, see Functions available to workers.

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 onmessage property to an appropriate event handler function.

var worker = new Worker('my_task.js');
worker.onmessage = function(event) {
 console.log("Called back by the worker!\n");

Alternatively, you could use addEventListener():

var worker = new Worker('my_task.js');
worker.addEventListener('message', function(event) {
 console.log("Called back by the worker!\n");
}, false);

worker.postMessage(); // start the worker.

Line 1 in this example creates a new worker thread,.  Line 2 sets up a listener to handle message events from the worker. This event handler will be called when the worker calls its own postMessage() function. Finally, Line 6 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 whether data URIs are of the same-origin or not; Gecko 10.0 (Firefox 10.0 / Thunderbird 10.0) and later do allow data URIs as a valid script for workers. Other browsers may disagree.

Passing data

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

Main app:

var worker = new Worker('my_task.js');
worker.onmessage = function(event) {
  console.log("Worker said:" +;


self.onmessage = function(event) {
  self.postMessage('Hi there!');
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.

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

Passing JSON data

It possible to pass JSON data (or any data type that can be serialized):

postMessage({'cmd': 'init', 'timestamp':});
Note: Objects passed in and out of workers must not contain functions or cyclical references, since JSON doesn't support these.

Advanced passing JSON Data and creating a switching system

If you have to pass some complex data and have to call many different functions both in the main page and in the Worker, you can create a system like the following.

example.html (the main page):

<!doctype html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>MDN Example - Queryable worker</title>
<script type="text/javascript">
    QueryableWorker instances methods:
     * sendQuery(queryable function name, argument to pass 1, argument to pass 2, etc. etc): calls a Worker's queryable function
     * postMessage(string or JSON Data): see Worker.prototype.postMessage()
     * terminate(): terminates the Worker
     * addListener(name, function): adds a listener
     * removeListener(name): removes a listener
    QueryableWorker instances properties:
     * defaultListener: the default listener executed only when the Worker calls the postMessage() function directly
  function QueryableWorker (sURL, fDefListener, fOnError) {
    var oInstance = this, oWorker = new Worker(sURL), oListeners = {};
    this.defaultListener = fDefListener || function () {};
    oWorker.onmessage = function (oEvent) {
      if ( instanceof Object &&"vo42t30") &&"rnb93qh")) {
      } else {,;
    if (fOnError) { oWorker.onerror = fOnError; }
    this.sendQuery = function (/* queryable function name, argument to pass 1, argument to pass 2, etc. etc */) {
      if (arguments.length < 1) { throw new TypeError("QueryableWorker.sendQuery - not enough arguments"); return; }
      oWorker.postMessage({ "bk4e1h0": arguments[0], "ktp3fm1":, 1) });
    this.postMessage = function (vMsg) {, vMsg);
    this.terminate = function () {;
    this.addListener = function (sName, fListener) {
      oListeners[sName] = fListener;
    this.removeListener = function (sName) {
      delete oListeners[sName];

  // your custom "queryable" worker
  var oMyTask = new QueryableWorker("myTask.js" /* , yourDefaultMessageListenerHere (optional), yourErrorListenerHere (optional) */);

  // your custom "listeners"

  oMyTask.addListener("printSomething", function (nResult) {
    document.getElementById("firstLink").parentNode.appendChild(document.createTextNode(" The difference is " + nResult + "!"));

  oMyTask.addListener("alertSomething", function (nDeltaT, sUnit) {
    alert("Worker waited for " + nDeltaT + " " + sUnit + " :-)");
    <li><a id="firstLink" href="javascript:oMyTask.sendQuery('getDifference', 5, 3);">What is the difference between 5 and 3?</a></li>
    <li><a href="javascript:oMyTask.sendQuery('waitSomething');">Wait 3 seconds</a></li>
    <li><a href="javascript:oMyTask.terminate();">terminate() the Worker</a></li>
Note: Objects passed in and out of workers must not contain functions or cyclical references, since JSON doesn't support these.

myTask.js (the Worker):

// your custom PRIVATE functions

function myPrivateFunc1 () {
  // do something

function myPrivateFunc2 () {
  // do something

// etc. etc.

// your custom PUBLIC functions (i.e. queryable from the main page)

var queryableFunctions = {
  // example #1: get the difference between two numbers:
  getDifference: function (nMinuend, nSubtrahend) {
      reply("printSomething", nMinuend - nSubtrahend);
  // example #2: wait three seconds
  waitSomething: function () {
      setTimeout(function() { reply("alertSomething", 3, "seconds"); }, 3000);

// system functions

function defaultQuery (vMsg) {
  // your default PUBLIC function executed only when main page calls the queryableWorker.postMessage() method directly
  // do something

function reply (/* listener name, argument to pass 1, argument to pass 2, etc. etc */) {
  if (arguments.length < 1) { throw new TypeError("reply - not enough arguments"); return; }
  postMessage({ "vo42t30": arguments[0], "rnb93qh":, 1) });

self.onmessage = function (oEvent) {
  if ( instanceof Object &&"bk4e1h0") &&"ktp3fm1")) {
  } else {
Note: Objects passed in and out of workers must not contain functions or cyclical references, since JSON doesn't support these.

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 contains an additional way to pass data to/from a worker using Transferable Objects with high performance. With transferable objects, data is 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. It's 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 contents are (quite literally) transferred to the Worker context.

Chrome includes an additional prefixed version of postMessage API that supports transferable objects. The first argument to the method is an ArrayBuffer, followed by an array of the items to transfer. 

// Create a 32MB "file" and fill it.
var uInt8View = new Uint8Array(1024*1024*32); // 32MB
for (var i = 0; i < uInt8View.length; ++i) {
  uInt8View[i] = i;

worker.webkitPostMessage(uInt8Array.buffer, [uInt8Array.buffer]);

For more information on transferable objects, see HTML5Rocks.

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.

Subworkers are currently not supported in Chrome. See

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:

<!doctype html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>MDN Example - Embedded worker</title>
<script type="text/js-worker">
  // This script WON'T be parsed by JS engines because its mime-type is text/js-worker.
  var myVar = "Hello World!";
  // Rest of your worker code goes here.
<script type="text/javascript">
  // This script WILL be parsed by JS engines because its mime-type is text/javascript.
  function pageLog (sMsg) {
    // Use a fragment: browser will only render/reflow once.
    var oFragm = document.createDocumentFragment();
<script type="text/js-worker">
  // This script WON'T be parsed by JS engines because its mime-type is text/js-worker.
  self.onmessage = function (oEvent) {
  // Rest of your worker code goes here.
<script type="text/javascript">
  // This script WILL be parsed by JS engines because its mime-type is text/javascript.

  // In the future...:
  // var oBuilder = new BlobBuilder();
  // ...but for now...:
  var oBuilder = new MozBlobBuilder();"script[type=\"text\/js-worker\"]"), function (oScript) { oBuilder.append(oScript.textContent); });

  // Creating a new document.worker property containing all our "text/js-worker" scripts.
  document.worker = new Worker(window.URL.createObjectURL(oBuilder.getBlob()));
  // Note: window.webkitURL.createObjectURL() in Chrome 10+.

  document.worker.onmessage = function (oEvent) {
    pageLog("Received: " +;

  // Start the worker.
  window.onload = function() { document.worker.postMessage(""); };
<body><div id="logDisplay"></div></body>
Note: BlobBuilder is not yet avaible. We used the MozBlobBuilder constructor instead.

The embedded worker is now nested into a new custom document.worker property.

Timeouts and intervals

Workers can use timeouts and intervals just like the main thread can.  This can be useful, for example, if you want to have your worker thread run code periodically instead of nonstop.

See setTimeout(), clearTimeout(), setInterval(), and clearInterval() for details.

Terminating a worker

If you need to immediately terminate a running worker, you can do so by calling the worker's terminate() method:


The worker thread is killed immediately without an opportunity to complete its operations or clean up after itself.

Workers may close themselves by calling their own nsIWorkerScope.close() method.

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:

A human-readable error message.
The name of the script file in which the error occurred.
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:

importScripts();                        /* imports nothing */
importScripts('foo.js');                /* imports just "foo.js" */
importScripts('foo.js', 'bar.js');      /* imports two scripts */

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 importScript() 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.


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.

var results = [];

function resultReceiver(event) {
  if (results.length == 2) {
    postMessage(results[0] + results[1]);

function errorReceiver(event) {

onmessage = function(event) {
  var n = parseInt(;

  if (n == 0 || n == 1) {

  for (var i = 1; i <= 2; i++) {
    var worker = new Worker("fibonacci.js");
    worker.onmessage = resultReceiver;
    worker.onerror = errorReceiver;
    worker.postMessage(n - i);

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 HTML code

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  <title>Test threads fibonacci</title>

  <div id="result"></div>

  <script language="javascript">

    var worker = new Worker("fibonacci.js");

    worker.onmessage = function(event) {
      document.getElementById("result").textContent =;
      dump("Got: " + + "\n");

    worker.onerror = function(error) {
      dump("Worker error: " + error.message + "\n");
      throw error;



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.

Finally, a message is sent to the worker to start it.

Try this example.

Performing web I/O in the background

You can find an example of this in the article Using workers in extensions.

Dividing tasks among multiple workers

As multi-core computers become increasingly common, it's often useful to divide computationally complex tasks among multiple workers, which may then perform those tasks on multiple-processor cores.

example coming soon

Creating workers from within workers

The Fibonacci example shown previously demonstrates that workers can in fact spawn additional workers.  This makes it easy to create recursive routines.

Browser compatibility

  • Desktop
  • Mobile

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Dedicated workers 3 3.5 (1.9.1) 10 10.60 4
Shared workers 5 --- --- 10.60 5
Passing data using structured cloning 13 8 10 11.50 5.1
Passing data using transferable objects 17 webkit --- --- --- ---
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
Dedicated workers --- 0.16 --- --- 11 5
Shared workers --- -- --- --- --- ---
Passing data using structured cloning --- 0.16 --- --- --- ---

Tags (5)

Edit tags

Attachments (0)


Attach file