Web Workers allows running code (JS file) in a background thread separate from the main execution thread of an app.
Time-intensive processing can be delegated to them not to block/slow down the main thread.
A worker is an object created using a constructor (e.g. Worker()) that runs JS file in the background thread.
Most of the standard JavaScript sets of functions are available from inside the worker. But there are some exceptions: for example, you can't access DOM (more details).
Communication between the worker and the main thread is done via a system of messages.
Both sides have a postMessage()
method to send their messages.
The onmessage
event handler is used to respond to the message (contained within the message event data
property).
The data is copied (using a structured clone algorithm) rather than shared.
- Dedicated workers - utilized by a single script.
- Shared workers - utilized by multiple scripts running in different windows, IFrames, etc., within the same domain.
- Service workers - act as proxy servers between the app, the browser, and the network.
A dedicated worker is created using the Worker() constructor, specifying the URL of a script to execute.
E.g.
const worker = new Worker('worker.js');
To start the demo run:
npm run start:worker
A shared worker is created using the SharedWorker() constructor, specifying the URL of a script to execute.
E.g.
const sharedWorker = new SharedWorker('shared-worker.js');
To start the demo run:
npm run shared-worker
A service worker is an event-driven worker. It can control the routes it is associated with by intercepting and modifying navigation and resource requests.
It is registered using the ServiceWorkerContainer.register() method.
E.g.
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js');
}
To start the demo run:
npm run service-worker
and then open http://localhost:8888/