Worker
The Worker
interface of the Web Workers API represents a background task that can be easily created and can send messages back to its creator. Creating a worker is as simple as calling the Worker()
constructor and specifying a script to be run in the worker thread.
Workers may in turn spawn new workers as long as those workers are hosted within the same origin as the parent page (Note: nested workers are currently not implemented in Blink). In addition workers may use XMLHttpRequest
for network I/O, with the stipulation that the responseXML
and channel
attributes on XMLHttpRequest
always return null
.
Not all interfaces and functions are available to the script associated with a Worker
.
In Firefox, if you want to use workers in extensions and would like to have access to js-ctypes, you should use the ChromeWorker
object instead.
Properties
Inherits properties from its parent, EventTarget
, and implements properties from AbstractWorker
(en-US).
Event handlers
AbstractWorker.onerror
(en-US)-
An
EventListener
called whenever anErrorEvent
(en-US) of typeerror
bubbles through to the worker. This is inherited fromAbstractWorker
(en-US). Worker.onmessage
(en-US)-
An
EventListener
called whenever aMessageEvent
of typemessage
bubbles through the worker — i.e. when a message is sent to the parent document from the worker viaDedicatedWorkerGlobalScope.postMessage
(en-US). The message is stored in the event'sdata
(en-US) property.
Constructors
Worker()
(en-US)-
Creates a dedicated web worker that executes the script at the specified URL. Workers can also be constructed using Blobs.
Methods
Inherits methods from its parent, EventTarget
, and implements properties from AbstractWorker
(en-US).
Worker.postMessage()
(en-US)-
Sends a message — which can consist of
any
JavaScript object — to the worker's inner scope. Worker.terminate()
-
Immediately terminates the worker. This does not offer the worker an opportunity to finish its operations; it is simply stopped at once. ServiceWorker instances do not support this method.
Example
The following code snippet shows creation of a Worker
object using the Worker()
(en-US) constructor and 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).
Especificaciones
Specification |
---|
HTML Standard # dedicated-workers-and-the-worker-interface |
Browser compatibility
BCD tables only load in the browser
Support varies for different types of workers. See each worker type's page for specifics.
See also
- Using web workers
- Functions available to workers
- Other kind of workers:
SharedWorker
(en-US) and ServiceWorker (en-US). - Non-standard, Gecko-specific workers:
ChromeWorker
, used by extensions.