![]() |
VOOZH | about |
HTML is a Markup language that is used to design web pages and JavaScript is a programming language that enables dynamic interactivity on websites when it is applied to an HTML. It helps users to build modern web applications.
But the problem with this JavaScript was designed to run in a single-threaded environment, so multiple scripts cannot run at the same time also when executing Javascript scripts on an HTML page, the page becomes unresponsive until the script is finished.
So, To overcome this Web worker comes into the picture. The Web Workers is a separate piece of JavaScript code that runs in the background of the web page without affecting it.
Table of Content
Web workers are multithreaded objects that are used to execute Javascript in the background without affecting the performance of the application or webpage. Web Workers allow for long-running scripts that are not interrupted by scripts that respond to clicks or other user interactions and allow long tasks to be executed without affecting the responsiveness of the web page. Generally, it is used for big CPU-intensive tasks.
Web Workers provide a way to run scripts in the background, separate from the main thread of your web page. They allow you to perform tasks without interfering with the user interface. Here are the two main types of Web Workers:
It is used to create a web worker
worker = new Worker("webWorker.js");
It is used to terminate a web worker.
worker.terminate();
Step 1: Create a Javascript file for Web Worker and the code which you want to run in the background. Here we are creating a webWorker.js file and using it to count from 1 in the background and show that to our web page and in the frontend, we will use the alert box.
Step 2: Now create an index.html and add the following codes to that file.
Output: In this program, Web Worker is counting numbers in the background and still, we can use our web page like here we have used the alert box.
Supported Browsers:
Note: Chrome doesn't let you load Web Workers when running scripts from a local file. So, for this use, a web host or you can use live server extension.