Back to: HTML Tutorials
Web Workers in HTML with Examples
In this article, I am going to discuss Web Workers in HTML with Examples. Please read our previous article, where we discussed Server-Sent Events (SSE) in HTML with Examples.
HTML5 Web Workers
A web worker is a JavaScript code that runs in the background and performs complicated operations without affecting the page’s performance.
What is a Web Worker?
Users prefer websites and applications that are fast and responsive and can perform multiple operations at the same time without compromising the page’s performance. However, when performing large operations, we frequently experience some delay in response or degraded performance. The Html Web Workers can be used to overcome this problem.
HTML5 introduced a new feature called web worker, which is designed to execute background work independently of other user-interface scripts.
Web Workers are multithreaded objects that can execute several JavaScript’s simultaneously without compromising the performance of the application or webpage. You can continue to do anything you want, such as browsing, purchasing products, streaming movies, and so on, while the web worker operates in the background.
The following are some of the most important characteristics of Web Workers:
- Threaded JavaScript is used to create web workers.
- Web workers are the kernel-level threads.
- Web workers take additional space and CPU time.
- Web-workers improve the speed of a website.
- On the client side, a web worker executes code.
- Web worker threads communicate with each other using the postMessage() callback mechanism.
Types of Web Workers in HTML
Web Workers in HTML5 are classified into two types:
- Dedicated Web Workers: The dedicated web worker can only be accessed by the script that is called it. The dedicated worker thread terminates when its parent thread terminates. Dedicated workers are used by only one or two primary threads.
- Shared Web Workers: It can be shared by multiple scripts and can communicate with each other via the port. Different windows, iframes, and workers can access shared workers.
Create a Web Worker File in HTML
The most basic application of web workers is to complete a time-consuming operation. So, in this tutorial, we’ll make a basic stopwatch that counts time in seconds. The postMessage() function and the onmessage event handler are responsible for all Worker thread communication. The “workers.js” file contains the stopwatch script.
if(typeof(Worker) !== "undefined") { if(typeof(w) == "undefined") { w = new Worker("demo_workers.js"); } w.onmessage = function(event) { document.getElementById("result").innerHTML = event.data; }; } else { document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Workers..."; }
Create a Web Worker Object in HTML
We’ve now created our web worker file. In this step, we will initiate the web worker from an HTML document, which will run the code in the file “worker.js” in the background and eventually display the result on the web page.
if (typeof(w) == "undefined") { w = new Worker("demo_workers.js"); }
Terminate a Web Worker in HTML
So far, we’ve learned how to create a worker and receive messages. On the other hand,a running worker can be terminated in the middle of an execution. When we create a web worker object, it will keep listening for messages until the user terminates it. The terminate() function can be used to terminate a web worker and free up browser/computer resources.
w.terminate();
HTML5 Web Worker Example
In the example below we have created a simple stopwatch with the help of a web worker.
<!DOCTYPE html> <html> <style> body{ display:flex; justify-content:center; align-items:center; flex-direction:column; height:100vh; font-size:32px; font-family:arial; background-color:mediumseagreen; } p{ display:flex; justify-content:center; align-items:center; flex-direction:column; color:#ffffff; font-weight:700; } .btndiv button{ background-color:#ffffff; outline:none; border:none; padding:10px; border-radius:8px;} output{ font-size:84px; color:yellow;} </style> <body> <p>Count in Seconds <br><output id="result">0</output></p> <div class="btndiv"> <button onclick="startCounter()">Start Counter</button> <button onclick="stopCounter()">Stop Counter</button> </div> <script> var w; function startCounter() { if(typeof(Worker) !== "undefined") { if(typeof(w) == "undefined") { w = new Worker("demo_workers.js"); } w.onmessage = function(event) { document.getElementById("result").innerHTML = event.data; }; } else { document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Workers..."; } } function stopCounter() { w.terminate(); w = undefined; } </script> </body> </html>
Output:
After Starting Counter
Here, in this article, I try to explain Web Workers in HTML with Examples and I hope you enjoy this Web Workers in HTML with Examples article.