Explain Web Worker in HTML
Last Updated :
25 Jul, 2024
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.
What is a Web Worker?
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.
Types of Web Workers
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:
1. Dedicated Workers:
- A dedicated worker is accessible only by the script that spawned it.
- It runs in its own thread, isolated from the main thread.
- Useful for scenarios where you want to offload heavy computations or time-consuming tasks without affecting the responsiveness of your web page.
- Dedicated workers are typically used within a single script.
2. Shared Workers:
- A shared worker can be accessed by multiple scripts running in different windows, iframes, or other contexts, as long as they are in the same domain.
- Shared workers are designed for scenarios where you need to share data or coordinate actions across different parts of your application.
- They provide a way to communicate and collaborate between different tabs or frames.
- Shared workers are more versatile and can be utilized by various scripts simultaneously.
Syntax for Creating a Web Worker
It is used to create a web worker
worker = new Worker("webWorker.js");
Syntax for Terminating a Web Worker
It is used to terminate a web worker.
worker.terminate();
Example of Web Worker
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.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Web Worker</title>
</head>
<body>
<p>Web Worker is Counting Numbers</p>
<p>Counting: <output id="countM"></output></p>
<button onclick="alertMessage()">
Alert On
</button>
<script>
// This is function to run alert
function alertMessage() {
alert("Web Worker is Running in Background");
}
// Created a web worker and passed script which
// needs to execute in background
var worker = new Worker("webWorkers.js");
// Called onmessage method to get value from
// script file and show it on web page
worker.onmessage = function (event) {
document.getElementById("countM")
.innerHTML = event.data;
};
</script>
</body>
</html>
JavaScript
// Initialized a variable with 0
var count = 0;
function timedCount() {
count = count + 1;
// It is used to send value
// back to html page
postMessage(count);
// It is a timeout function
setTimeout("timedCount()", 1000);
}
timedCount();
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:
- Google Chrome 4.0
- Firefox 3.5
- Microsoft Edge 10.0
- Safari 4.0
- Opera 11.5
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.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
HTML Tutorial HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript
11 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
AVL Tree Data Structure An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read