Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
The web workers API(Application Programming Interface) is a JavaScript API that runs in the background, independent of other scripts, and does not slow down or impact the page's performance.
We'll look at how we can use the Web Worker on our website to prevent thread blocking while performing CPU-intensive tasks.
Web Workers API
Because Javascript is a single-threaded language, it causes the site to become unresponsive while scripts are being executed.
To prevent interfering with the site's interaction, we can deploy a worker that will run the scripts in the background. Therefore, we will be able to improve the performance of our website.
While the web worker is running in the background, you can continue to do whatever you want: click, select objects, etc. A background thread that separates from the main execution thread of the web application is used by Web Workers.
Note: Web Workers are a browser functionality that can be accessible by JavaScript, and they are not a part of JavaScript. Most browsers have been single-threaded in the past (this has, of course, changed), and most JavaScript implementations take place in the browser.
Node.JS does not have a concept of "web workers"; instead, it has a concept of "cluster" or "child process," which is slightly different.
Web browser Versions supporting Web Workers API
Chrome 4 (Since January 2010)
Firefox 3.5 (Since June 2009)
IE(Internet Explorer) 10 (Since September 2012)
Opera 11.5 (Since June 2011)
Safari 4 (Since June 2009)
Implementing Web Worker
We will check whether the user's browser supports the web workers before generating a web worker:
// Supports the web workers
if(typeof(Worker) !== "undefined"){
// Code
}
// No support for web workers
else{
// Code
}
You can also try this code with Online Javascript Compiler
With the help of a simple example below, we will be able to understand the implementation fully. The worker script will receive a number from the parent script and calculate the square root of that number before returning to the parent script.
We can communicate and handle issues using event listeners in the worker object and worker script.
Generate a Web Worker file
Web Workers are implemented as .js scripts that are included in your page through asynchronous HTTP requests. The Web Workers API hides these queries from you totally.
To achieve parallelism, workers use thread-like message forwarding. They're ideal for keeping your user interface up to date, fast, performant, and responsive.
In the browser, Web Workers run in a separate thread. As a result, the code they execute must be kept distinct from the rest of the program. It is very necessary to keep it in mind.
We're going to make a parent script that will pass down a number to the worker script. The worker script will then calculate the square root of a number and return back to the parent script. The script may be found in the file "demoWorkers.js":
Parent script
The main thread will be used to run this javascript file.
Create a Worker:
// To create a new worker object here
var demoWorker = new Worker("./demoWorker.js")
You can also try this code with Online Javascript Compiler
You'll want to handle any errors your web workers throw, just like you would with any JavaScript logic. An ErrorEvent is fired if an error occurs while a worker is running. The interface has three properties that can help you figure out what went wrong:
lineno - the line number where the error has occurred,
message - a coherent or meaningful explanation of the error, and
filename - Name of the worker script file that generated the problem or error.
Send data to Worker:
// To send data to the worker script
demoWorker.postMessage(data);
// To send data from a worker to a JavaScript file
self.postMessage(data);
You can also try this code with Online Javascript Compiler
The postMessage() method, which is used to post a message back to the HTML page, is the most significant component of the code above.
Let's create an event listener for the message event and access it via the data key to receive data from a worker or the main thread:
// To receive data from a JavaScript file
self.onmessage = (e) => {
console.log(e.data);
}
// To receive data from a worker
demoWorker.onmessage = (e) => {
console.log(e.data);
}
You can also try this code with Online Javascript Compiler
It's important to note that data sent between a worker and the main thread is copied rather than shared.
To terminate the Worker:
The creation of a Web Worker causes real threads to be created on the user's computer, consuming system resources. As a result, terminating a worker when it has completed its role is a smart idea. The terminate() method on a worker can be used to terminate the worker. This terminates the worker immediately, regardless of whether it is executing a task or not. Within its scope, a worker can also be terminated. To do so, use the worker's close() method as follows:
// To immediately terminate the worker script
demoWorker.terminate();
// To close a worker from itself
self.close();
You can also try this code with Online Javascript Compiler
// To take data from the parent script
self.onmessage = function (e) {
// To access data from the event object
const value = Math.sqrt(e.data);
// To send data to the parent script
self.postMessage(value);
};
// It fires or shows an error when the message cannot be deserialized
self.onmessageerror = function (e) {
...
};
You can also try this code with Online Javascript Compiler
Note: Web workers are typically employed for more CPU-intensive tasks rather than simple scripts.
The DOM and Web Workers
Web workers don’t have access to the following JavaScript objects since they are in external files:
Document Object
Window Object
Parent Object
Types of Web Worker
The Dedicated Workers
Only the script that invoked it has access to a dedicated worker. For example, you can input two numbers to be multiplied together in the field. The numbers are transferred to a specialized worker, who multiplies them together and returns the result to the page, which is then displayed.
The Shared Workers
Shared workers are the workers that can be reached by all processes running on the same origin(iframes, different browser tabs, or other shared workers).
Multiple scripts can access a shared worker, even if they are accessed through distinct windows, iframes, or even workers. This is pretty similar to the basic dedicated worker example, except it has two functions: multiplying two numbers and squaring a number, both handled by separate script files. The same worker does the actual calculation in both scripts.
The Service Workers
Service Workers function as intermediary servers between web applications, the browser, and the network (when available). They are designed to enable the creation of effective offline experiences, take appropriate action based on whether the network is available, intercept network requests, and updated assets are stored on the server, among other things. They'll also give you access to APIs for push alerts and background synchronization.
Frequently Asked Questions
Why should we use Javascript Web Workers?
Ans: Using web workers and parallel programming in JavaScript, you can perform numerous operations simultaneously. Web workers allow you to construct background threads independent of the main execution thread, where the user interface logic is normally executed. The fundamental benefit of workload separation is that you may conduct expensive activities in a separate thread without interrupting or compromising the main thread's responsiveness and usefulness. When the background thread finishes its task, it tells the main thread of the results via an event controlled using standard JavaScript event handling.
2. List down some limitations of the web worker API.
Ans: Although the Web Workers API is a great tool, it does have certain limitations:
A worker can't directly change the DOM and only has limited access to the window object's methods and properties.
It is not possible to run a worker directly from the filesystem. It is only possible to execute it on a server.
Key Takeaways
In this blog, we learned how to make web workers API from scratch. We also learned how to send and receive messages between two threads and how to react to them. We made a passing reference to terminating web workers. This final operation should be approached with caution, as improperly terminated web workers can cause memory leaks in a web page.