Esta tradução está incompleta. Por favor, ajude a traduzir este artigo do Inglês.

A interface do Worker da API de Workers da Web representa uma tarefa em segundo palno que pode ser criada facilmente e pode enviar mensagens de volta para o seu criador. Criar um worker é tão simples como chamar o criador de Worker() e especificar um script para ser executado na sequência do worker.

Os workers podem, por sua vez, gerar novos workers enquanto esses workers estiverem alojados dentro da mesma origem como a página original (Nota: os workers integrados não estão atualmente implementados no Blink).  Em adição os workers poderão utilizar XMLHttpRequest para I/O rede, com a estipulação que a responseXML e os atributos channel no XMLHttpRequest retornam sempre null.

Nem todas as interfaces e funções estão disposníveis para o script associado com um Worker.

No Firefox, se quiser utilziar os workers nas extensões e pretender ter acesso a js-ctypes, então deverá utilizar o objeto ChromeWorker.

Criadores

Worker()
Creates a dedicated web worker that executes the script at the specified URL. Workers can also be constructed using Blobs.

Propriedades

Inherits properties from its parent, EventTarget, and implements properties from AbstractWorker.

Manipuladores de evento

AbstractWorker.onerror
An EventListener called whenever an ErrorEvent of type error bubbles through to the worker. This is inherited from AbstractWorker.
Worker.onmessage
An EventListener called whenever a MessageEvent of type message bubbles through the worker — i.e. when a message is sent to the parent document from the worker via DedicatedWorkerGlobalScope.postMessage. The message is stored in the event's data property.
Worker.onmessageerror
Is an EventHandler representing the code to be called when the messageerror event is raised.

Métodos

Inherits methods from its parent, EventTarget, and implements methods from AbstractWorker.

Worker.postMessage()
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.

Exemplo

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

var myWorker = new Worker('worker.js');
var first = document.querySelector('#number1');
var second = document.querySelector('#number2');

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

Especificações

Especificação Estado Comentário
HTML Living Standard
The definition of 'Worker' in that specification.
Living Standard  

Compatibilidade de navegador

Support varies for different types of workers. See each worker type's page for specifics.

Funcionalidade Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 4 (Yes) 3.5 10.0 10.6 4
Constructor name option (Yes) ? 55 (55) ? ? ?
onmessageerror 60 ? 57 (57) No support ? ?
Feature Android Edge Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile Chrome for Android
Basic support 4.4 (Yes) 3.5 10.0 11.5 5.1 ?
Constructor name option ? ? 55.0 (55) ? ? ? (Yes)
onmessageerror 60 ? 57.0 (57) No support ? ? ?

Cross-origin worker error behaviour

In earlier browser versions, trying to load a cross-origin worker script threw a SecurityError; in newer browsers an error event is thrown instead due to a spec change. Find out more information on how to deal with this in Loading cross-origin worker now fires error event instead of throwing; worker in sandboxed iframe no longer allowed.

Consultar também

Etiquetas do documento e contribuidores

 Contribuidores para esta página: mansil
 Última atualização por: mansil,