Name
Worker — a worker thread
Inherits from
EventTarget
Synopsis
A Worker represents a background thread. Create a new Worker
with the Worker()
constructor,
passing the URL of a file of JavaScript code for it to run. The
JavaScript code in that file can use synchronous APIs or perform
compute-intensive tasks without freezing up the main UI thread.
Workers run their code in a completely separate execution context
(see WorkerGlobalScope), and the only way to
exchange data with a worker is via asynchronous events. Call
postMessage()
to send data to the
Worker, and handle message events to receive data from the
worker.
See Web Workers for an introduction to worker threads.
Constructor
new
Worker
(
string
scriptURL
)
Constructs a new Worker object and causes it to run the
JavaScript code in scriptURL
.
Methods
void postMessage
(any
message
, [MessagePort[]
ports
])
postMessage
(any
message
, [MessagePort[]
ports
])Send message
to the worker, which
will receive it as a MessageEvent object sent to its on
message
handler.
message
can be a JavaScript primitive
value or object or array, but not a function. Client-side types
ArrayBuffer, File, Blob, and ImageData are allowed, but Nodes,
such as Document and Element, are not allowed (see Structured Clones for details).
The optional ports
argument is an
advanced feature that allows you to pass one or more direct
communication channels to the Worker. If you create two Worker
objects, for example, you can allow them to communicate directly
with each other by passing them each one end of a MessageChannel.
void
Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.