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: