Web worker specification defines an API for spawning background scripts in our web application.
Web workers allow us to do things like fire up long-running scripts to handle computationally intensive tasks, without blocking the UI or other scripts to handle user interactions.
Workers utilize thread-like message passing to achieve parallelism. They’re perfect for keeping our UI refresh, and responsive for users.
We can run whatever code we like inside worker thread, with some exceptions.
For example, we cannot directly manipulate the DOM from inside a worker or use some default methods and properties of the window object. Instead we can use a large number of items available under the window, including WebSockets and data storage mechanisms like IndexedDB.
Data is sent to workers and to 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 handlers.
Workers may, in turn, spawn new workers, as long as those workers are hosted within the same origin as the parent page.
The worker context is represented by a DedicatedWorkerGlobalScope object in the case of dedicated workers (workers that are utilized by a single script; shared workers use SharedWorkerGlobalScope).
A dedicated worker is only accessible from the script that first spawned it, whereas shared workers can be accessed from multiple scripts.