Worker()

The Worker() constructor creates a Worker object that executes the script at the specified URL. This script must obey the same-origin policy.

If the URL has an invalid syntax or if the same-origin policy is violated a DOMException of type SECURITY_ERR is thrown.

Note: that there is a disagreement among browser manufacturers about whether a data URI is of the same origin or not. Though Gecko 10.0 (Firefox 10.0 / Thunderbird 10.0 / SeaMonkey 2.7) and later accept data URIs, that's not the case in all other browsers.

Syntax

var myWorker = new Worker(aURL);

Parameters

aURL
Is a DOMString representing the URL of the script the worker will execute. It must obey the same-origin policy.

Return value

The created worker.

Exceptions

  • SecurityError is raised if the document is not allowed to start workers
  • NetworkError is raised if the MIME type of one of the script is text/csv, image/*, video/*, or audio/*. It should always be text/javacript.
  • SyntaxError is raised if aURL cannot be parsed.

Example

The following code snippet shows creation of a Worker object using the Worker() constructor and subsequent usage of the object:

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

first.onchange = function() {
  myWorker.postMessage([first.value,second.value]);
  console.log('Message posted to worker');
}

For a full example, see ourBasic dedicated worker example (run dedicated worker).

Specifications

Specification Status Comment
WHATWG HTML Living Standard
The definition of 'Worker()' in that specification.
Living Standard No change from Web Workers.
Web Workers
The definition of 'Worker()' in that specification.
Editor's Draft Initial definition.

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 4 3.5 10.0 10.6 4
Feature Android Firefox Mobile (Gecko) Firefox OS (Gecko) IE Phone Opera Mobile Safari Mobile
Basic support 4.4 3.5 1.0.1 10.0 11.5 5.1

See also

The Worker interface it belongs to.

Document Tags and Contributors

 Contributors to this page: teoli, Jeremie, chrisdavidmills, kscarfone
 Last updated by: teoli,