JavaScript Reference ยท Browser and Web APIs
Web Workers
Reference for Web Workers: creating a Worker, postMessage(), structured cloning, transferables, terminate(), error handling and when a worker helps.
A Web Worker runs JavaScript on a separate thread, so heavy work such as parsing a large file or crunching numbers does not freeze the page. The main thread creates a worker with new Worker(url), and the two sides talk by sending messages with postMessage() and listening for message events.
A worker has no access to the DOM, window or document. It has its own global scope (self), plus timers, fetch(), IndexedDB, WebSocket and the ability to start more workers. Data is copied between threads by the structured clone algorithm, not shared.
const worker = new Worker("worker.js"); worker.postMessage({ numbers: [1, 2, 3] }); worker.onmessage = (event) => console.log(event.data);
Try it
A worker needs a script file or a blob: URL. The sandboxed editors on this site may refuse to start one, so the first example reports what happens. The second example uses a MessageChannel, which has the same postMessage() interface, to show the messaging model without a thread.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
const worker = new Worker(scriptURL, options) worker.postMessage(message, transferList) worker.terminate() // inside the worker self.onmessage = (event) => { /* event.data */ } self.postMessage(result) self.close() importScripts("helper.js") // classic workers only
| Name | Description |
|---|---|
scriptURL |
URL of the worker script. It must be same-origin, or a blob: or data: URL where allowed. |
options.type |
"classic" (default) or "module", which allows import inside the worker. |
options.name |
A name for debugging, available as self.name in the worker. |
message |
Any value the structured clone algorithm supports: objects, arrays, Maps, Sets, Dates, typed arrays, Blobs and more. Functions and DOM nodes cannot be cloned. |
transferList |
Optional array of transferable objects, such as ArrayBuffer or MessagePort, whose ownership moves instead of being copied. |
Events: message (data arrived), messageerror (data could not be deserialized) and error (an uncaught exception in the worker).
Exceptions: new Worker() throws a SecurityError for a disallowed URL and a SyntaxError for an invalid one. postMessage() throws DataCloneError when the value cannot be cloned.
Usage notes
- Messages are copies. Changing an object after posting it does not affect the other side. Large copies cost time.
- Transfer big buffers.
worker.postMessage(buffer, [buffer])moves anArrayBufferwith no copy; afterwards the sender's buffer is detached with length 0. - No DOM. Do computation in the worker and let the main thread update the page.
- One message at a time. A worker runs one task at a time; give it a queue or a pool for parallel jobs.
- Always clean up. Call
worker.terminate()from outside orself.close()from inside when done. Terminating stops the worker immediately without cleanup. - Workers cost memory and startup time. Use them for tasks that take tens of milliseconds or more, not for tiny jobs.
- Related types:
SharedWorkershares one worker between tabs;SharedArrayBuffershares memory but needs cross-origin isolation headers.
Browser support
Dedicated workers are supported in all current browsers. Module workers and SharedWorker have somewhat less uniform support, so check a compatibility table.