HTML Web Workers
Web structure starts with solid HTML. Learn how HTML Web Workers contributes to accessible and semantic web pages in the tutorial below.
Web Workers are independent blocks of JavaScript code that execute in the background of a web page without disrupting the user interface.
What is Web Worker?
Achieving a website or application that operates swiftly and can handle multiple tasks concurrently without compromising performance is a common goal. Nevertheless, instances may arise where there are delays in response or a decline in page performance, particularly when undertaking substantial operations. To address this issue, Web Workers can be employed.
Web Workers are a type of object in JavaScript that enable the execution of multiple scripts concurrently, allowing for parallel processing without causing any negative impact on the performance of the application or webpage.
Following are some key features of the Web Workers:
- Web-workers are threaded JavaScript.
- Web-workers are the kernel-level thread.
- Web-workers requires more space and CPU time.
- Web-workers enhances the speed of a website.
- Web-worker executes codes on the client side (not server-side).
- Web worker threads communicate with each other using postMessage callback method
Tips: Before working with HTML Web Workers you must have knowledge of JavaScript as the Web Worker depends on JavaScript.
Types of Web Workers:
In HTML5, Web Workers come in two varieties:
- Dedicated Web Workers:
Access to the dedicated worker is restricted to the script that initiated it, and it terminates along with its parent thread. Dedicated workers are exclusively utilized by a singular main thread.
- Shared Web Workers:
Shared workers are capable of being utilized by various scripts and can establish communication through a designated port. They are accessible to diverse windows, iframes, or other workers.
Note: In this section, we will use dedicated Web Workers.
Web Workers Browser Support:
Prior to delving into web Workers, it is important to verify the browser support. Below is a code snippet that can be used to ascertain if your browser supports web Workers or not.
Example
<!DOCTYPE html>
<html>
<head>
<title>Web Worker API</title>
</head>
<body>
<h2>Example to check the browser support of Web Workers</h2>
<div id="supported"></div>
<div id="unsupported"></div>
<button onclick="worker();">click me</button>
<script type="text/javascript">
function worker()
{
if(typeof(Worker)!=="undefined"){
document.getElementById("supported").innerHTML="Supporting the browser";
}
else
{
document.getElementById("unsupported").innerHTML="Not supporting";}
}
</script>
</body>
</html>
Creation of Web worker file:
In order to generate a Web Worker file, it is necessary to develop a separate JavaScript file.
Below is a web worker file that has been developed to compute the square of a given number. This file has been named "worker.js".
Below is the code for worker.js file.
onmessage =function(event){
var num= event.data;
var sqr=num*num;
var result="";
for(var i=1;i<=sqr; i++)
{
result= "Sqaure result is:"+ " "+i;
}
postMessage(result);
}
Creating the Web Worker Object:
Within the "worker.js" file mentioned earlier, we have established the JavaScript file designed for a web Worker. The next step involves invoking this file within an HTML document. In order to instantiate the web worker object, it is essential to utilize the Worker constructor.
Below is the format used to instantiate and create a Web Worker object:
var worker= new Worker('worker.js');
Sending messages between the Worker thread and main thread:
The communication in the Worker thread relies on the utilization of the postMessage method and the onmessage event handler.
Terminating the Web Worker:
To stop the execution of the worker currently running in the main thread without delay, you can use the terminate function of Web Worker. Below is the format for terminating a web worker:
worker.terminate();
The termination of a Web Worker within the worker thread is also achievable by invoking the close function.
Example
<!DOCTYPE html>
<html>
<head>
<style>
.div1{
margin-left: 350px;
}
</style>
</head>
<body>
<!-- Sqaure Output Result -->
<div class="div1">
<h2>Example of Web Worker</h2>
<label>Enter the number to find the square</label>
<br><input type="text" name="num" id="num"><br>
<br><button id="submit">Submit</button>
<button id="other">Wait</button>
<div id="text"></div>
</div>
<script type="text/javascript">
document.getElementById("other").onclick=function() {
alert("Hey! Web Worker is working, and you can wait for the result.");
}
//Web-worker Code.....
var worker= new Worker("worker.js");
worker.onmessage= function(event){
document.getElementById("text").innerText= event.data;}
document.getElementById("submit").onclick= function(){
var num= document.getElementById("num").value;
worker.postMessage(num);
}
</script>
<p><b>Note:Try to enter a big number, and then click on other button. The page will respond properly</b></p>
</body>
</html>
Worker.js file:
onmessage=function(event){
var num= event.data;
var sqr=num*num;
var result="";
for(var i=1;i<=sqr; i++)
{
result= "Sqaure result is:"+ " "+i;
}
postMessage(result);
}
Example Explanation:
In the above example in HTML file we have used
- var worker= new Worker("worker.js"); To create the web Worker object.
- worker.onmessage= function(event): It is used to send the message between the main thread and Worker thread.
- worker.postMessage(num); This is the method used to communicate between the Worker thread and main thread. Using this method Worker thread return the result to the main thread.
Browser Support:
| API | Chrome | IE | Firefox | Opera | Safari |
|---|---|---|---|---|---|
| Web Workers | Yes | Yes | Yes | Yes | Yes |