Web-Workers

A web worker is a JavaScript that runs in the background. Independent of other scripts, without affecting the performance of the page.



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.

A worker is an object created using a constructor 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 current ‘window’.

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.

Types

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.

Tagged as: ,