MDN’s new design is in Beta! A sneak peek:

Web Workers API

Перевод не завершен. Пожалуйста, помогите перевести эту статью с английского.

Web Workers are a mechanism by which a script operation can be made to run in a background thread separate from the main execution thread of a web application. The advantage of this is that laborious processing can be performed in a separate thread, allowing the main (usually the UI) thread to run without being blocked/slowed down.

Концепции и использование Web воркеров

A worker is an object created using a constructor (e.g. Worker()) that runs a named JavaScript file — this file contains the code that will run in the worker thread; workers run in another global context that is different from the current window. This context is represented by a DedicatedWorkerGlobalScope object in the case of dedicated workers (standard workers that are utilized by a single script; shared workers use SharedWorkerGlobalScope).

You can run whatever code you like inside the worker thread, with some exceptions. For example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the window object. But you can use a large number of items available under window, including WebSockets, and data storage mechanisms like IndexedDB and the Firefox OS-only Data Store API.  See Functions and classes available to workers for more details.

Data is sent between workers and the main thread via a system of messages — both sides send their messages using the postMessage() method, and respond to messages via the onmessage event handler (the message is contained within the Message event's data attribute.) The data is copied rather than shared.

Workers may in turn spawn new workers, as long as those workers are hosted within the same origin as the parent page.  In addition, workers may use XMLHttpRequest for network I/O, with the exception that the responseXML and channel attributes on XMLHttpRequest always return null.

In addition to dedicated workers, there are other types of worker:

  • Shared workers are workers that can be utilized by multiple scripts running in different windows, IFrames, etc., as long as they are in the same domain as the worker. They are a little more complex than dedicated workers — scripts must communicate via an active port. See SharedWorker for more details.
  • ServiceWorkers essentially act as proxy servers that sit between web applications, and the browser and network (when available). They are intended to (amongst other things) enable the creation of effective offline experiences, intercepting network requests and taking appropriate action based on whether the network is available and updated assets reside on the server. They will also allow access to push notifications and background sync APIs.
  • Chrome Workers are a Firefox-only type of worker that you can use if you are developing add-ons and want to use workers in extensions and have access to js-ctypes in your worker. See ChromeWorker for more details. 
  • Audio Workers provide the ability for direct scripted audio processing to be done inside a web worker context.

Замечание: В соответствии с Web workers Spec, события ошибок воркеров не должны "всплывать" (смотрите  баг 1188141. Такое поведение было реализовано в Firefox 42.

Интерфейсы Web воркера

Abstracts properties and methods common to all kind of workers (i.e. Worker or SharedWorker).
Represents a running worker thread, allowing you to pass messages to the running worker code.
Represents a specific kind of worker that can be accessed from several browsing contexts, being several windows, iframes or even workers.
Represents the generic scope of any worker (doing the same job as Window does for normal web content). Different types of worker have scope objects that inherit from this interface and add more specific features.
Represents the scope of a dedicated worker, inheriting from WorkerGlobalScope and adding some dedicated features.
Represents the scope of a shared worker, inheriting from WorkerGlobalScope and adding some dedicated features.
Represents the identity and state of the user agent (the client):


Мы создали пару простых демонстрационных программ чтобы показать основы использования:

Больше информации о том, как работают эти демонстрационные программы, вы можете найти в статье Использование Web воркеров.


Спецификация Статус Комментарий
WHATWG HTML Living Standard Живой стандарт Не отличается от Web Workers.
Web Workers Редакторский черновик Initial definition.

Совместимость с браузерами

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Базовая поддержка 4 3.5 (1.9.1) 10.0 10.6 4
Разделяемые воркеры 4 29 (29) Нет 10.6 4
Передача данных через использование структурного клонирования 13 8 (8) 10.0 11.5 6
Передача данных с использованием передаваемых объектов 17 webkit
18 (18) Нет 15 6
Глобальный URL 10[1]
21 (21) 11 15 6[1]
Feature Android Chrome for Android Firefox Mobile (Gecko) Firefox OS (Gecko) IE Phone Opera Mobile Safari Mobile
Базовая поддержка 4.4 4 1.0 (1.9.1) 1.0.1 10.0 11.5 5.1
Разделяемые воркеры Нет 4 29 1.4 Нет Нет Нет
Передача данных через использование структурного клонирования Нет 4 8 1.0.1 Нет Нет Нет
Передача данных с использованием передаваемых объектов Нет Нет 18 1.0.1 Нет Нет Нет

[1] Как webkitURL.

Смотрите также

Метки документа и участники

 Внесли вклад в эту страницу: utking, Sebastianz
 Обновлялась последний раз: utking,