- Web Workers API
- Web Workers concepts and usage
- Worker types
- Worker global contexts and functions
- Supported Web APIs
- Web Worker interfaces
- Examples
- Specifications
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- Worker
- Constructors
- Instance properties
- Instance methods
- Events
- Example
- Specifications
- Browser compatibility
- Cross-origin worker error behavior
- See also
- Found a content problem with this page?
Web Workers API
Web Workers makes it possible to run a script operation 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 Workers concepts and usage
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.
In addition to the standard JavaScript set of functions (such as String , Array , Object , JSON , etc.), you can run almost any code you like inside a worker thread. There are 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. For information about the code that you can run see worker global context and functions, and supported web APIs below.
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 property). 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 .
Worker types
There are a number of different types of workers:
- Dedicated workers are workers that are utilized by a single script. This context is represented by a DedicatedWorkerGlobalScope object.
- 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.
- Service Workers essentially act as proxy servers that sit between web applications, the browser, and the network (when available). They are intended, among other things, to enable the creation of effective offline experiences, intercept network requests and take appropriate action based on whether the network is available, and update assets residing on the server. They will also allow access to push notifications and background sync APIs.
Note: As per the Web workers Spec, worker error events should not bubble (see Firefox bug 1188141. This has been implemented in Firefox 42.
Worker global contexts and functions
Workers run in a different global context than the current window ! While Window is not directly available to workers, many of the same methods are defined in a shared mixin ( WindowOrWorkerGlobalScope ), and made available to workers through their own WorkerGlobalScope -derived contexts:
Some of the functions (a subset) that are common to all workers and to the main thread (from WindowOrWorkerGlobalScope ) are:
- atob()
- btoa()
- clearInterval()
- clearTimeout()
- dump() Non-standard
- queueMicrotask()
- setInterval()
- setTimeout()
- structuredClone()
- window.requestAnimationFrame (dedicated workers only)
- window.cancelAnimationFrame (dedicated workers only)
The following functions are only available to workers:
Supported Web APIs
Note: If a listed API is supported by a platform in a particular version, then it can generally be assumed to be available in web workers. You can also test support for a particular object/function using the site: https://worker-playground.glitch.me/
The following Web APIs are available to workers:
- Barcode Detection API
- Broadcast Channel API
- Cache API
- Channel Messaging API
- Console API
- Web Crypto API (e.g. Crypto )
- CSS Font Loading API
- CustomEvent
- Encoding API (e.g. TextEncoder , TextDecoder )
- Fetch API
- FileReader
- FileReaderSync (only works in workers!)
- FormData
- ImageBitmap
- ImageData
- IndexedDB
- Media Source Extensions API (dedicated workers only)
- Network Information API
- Notifications API
- OffscreenCanvas (and all the canvas context APIs)
- Performance API , including:
- Performance
- PerformanceEntry
- PerformanceMeasure
- PerformanceMark
- PerformanceObserver
- PerformanceResourceTiming
Workers can also spawn other workers, so these APIs are also available:
Web Worker interfaces
Represents a running worker thread, allowing you to pass messages to the running worker code.
Defines the absolute location of the script executed by the Worker .
Represents a specific kind of worker that can be accessed from several browsing contexts (i.e. windows, tabs, or iframes) or even other 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).
Examples
We have created a couple of demos to show web worker usage:
You can find out more information on how these demos work in Using Web Workers.
Specifications
See also
Found a content problem with this page?
This page was last modified on Jul 5, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.Worker
The Worker interface of the Web Workers API represents a background task that can be created via script, which can send messages back to its creator.
Creating a worker is done by calling the Worker(«path/to/worker/script») constructor.
Workers may themselves spawn new workers, as long as those workers are hosted at the same origin as the parent page.
Not all interfaces and functions are available to scripts inside a Worker . Workers may use XMLHttpRequest for network communication, but its responseXML and channel attributes are always null . ( fetch is also available, with no such restrictions.)
Constructors
Worker() Creates a dedicated web worker that executes the script at the specified URL. This also works for Blob URLs.
Instance properties
Instance methods
Inherits methods from its parent, EventTarget . Worker.postMessage() Sends a message — consisting of any JavaScript object — to the worker’s inner scope. Worker.terminate() Immediately terminates the worker. This does not let worker finish its operations; it is halted at once. ServiceWorker instances do not support this method.
Events
error Fires when an error occurs in the worker. message Fires when the worker’s parent receives a message from that worker. messageerror Fires when a Worker object receives a message that can’t be deserialized. rejectionhandled Fires every time a Promise rejects, regardless of whether or not there is a handler to catch the rejection. unhandledrejection Fires when a Promise rejects with no handler to catch the rejection.
Example
The following code snippet creates a Worker object using the Worker() constructor, then uses the worker object:
const myWorker = new Worker("/worker.js"); const first = document.querySelector("input#number1"); const second = document.querySelector("input#number2"); first.onchange = () => myWorker.postMessage([first.value, second.value]); console.log("Message posted to worker"); >;
Specifications
Browser compatibility
Cross-origin worker error behavior
In early versions of the spec, loading a cross-origin worker script threw a SecurityError . Nowadays, an error event is thrown instead.
See also
Found a content problem with this page?
This page was last modified on Mar 16, 2023 by MDN contributors.
Your blueprint for a better internet.