What are Web Workers in JavaScript?
Web Workers are a simple API that runs in the background of a web application, without affecting the performance of the application. They allow long-running scripts to handle their tasks without blocking the UI or other scripts that handle user interactions. JavaScript is a single-threaded language and Web Workers allow multi-threading.
As Web Workers run in an isolated thread, the code that they execute needs to be contained in a separate file. However, before writing a Web Worker, it’s necessary to create a new Worker object in the main page script.
The object is created using the Worker constructor:
var worker = new Worker('workerExample.js');
Web Workers and their parent page communicate via postMessage() method, which can accept either a string or JSON object as its single argument depending on the browser version.
This is how a string is passed from the main page script to the worker script:
var worker = new Worker('workerExample.js');worker.addEventListener('message', function(event) {console.log('Worker prints out: ', event.data); //the message 'Hello World' is sent through event.data}, false);worker.postMessage('Hello World');
The workerExample.js file returns the message that the main script passed to it:
self.addEventListener('message', function(event) {self.postMessage(event.data); //the worker accepts 'Hello World' through event.data}, false);
There are several things to note about Web Workers:
- Web Workers do not have access to the DOM, window object, document object or parent object.
- They can be stopped using worker.terminate() from the main script or self.close() inside the worker script itself.
- A Worker's global scope object has a distinct event loop and its task queues have events, callbacks, and networking activity as tasks.
- While executing, Workers never block main event loop.