Loading Please Wait...

Logo Lynxsia IT Solutions

HTML Web Worker API

HTML Web Worker API

HTML web worker API allow us to execute (run) JavaScript in the background, without affecting the performance of the current running page.

When we execute (run or load) JavaScript on HTML page, it stop the page from loading and execute the script. After that it restart the loading of the page making HTML page unresponsive until the script is not finished.

While web worker API execute the script on the background so we can perform actions on the page like button click, without interfering the script.

Check For Web Worker Support

First of all, we need to check whether web worker is supported or not.

					 
        
          if(typeof(Worker) !== "undefined"){
            alert('Web worker supported.');
          } else {
            alert('Web worker not supported.');
          }
        
      
Creating Web Worker

Creating web working is just creating JavaScript file to perform some task. In web worker files complex task such as calling APIs, complex calculations, etc, are going to perform which consume lots of resource.

Create a JavaScript file named "worker.js" (or whatever name you want to give, just careful with ".js" extension) in the same directory (or where you want to, just careful in linking the file).

					 
        
          function getTime(){
            var datetime = new Date();
            var year = datetime.getFullYear();
            var month = datetime.getMonth();
            var date = datetime.getDay();
            var hours = datetime.getHours();
            var minutes = datetime.getMinutes();
            var seconds = datetime.getSeconds();
            var datetimeFormat = date + "-" + month + "-" 
                 + year + " " + hours + ":" + minutes + ":" + seconds + ":";
            postMessage(datetimeFormat);
            setTimeout("getTime()", 1000);
          }
          getTime();
        
      
Code Explanation

The above code get the current time and regularly update it.

The new Date() get the current date and time. The year, month, date, hours, minutes, and seconds defined to format the date.

The postMessage() method is the important part of web worker which post the message back to HTML document.

The setTimeout() method calls the getTime() method every 1000 milliseconds (1 second).

Creating Web Worker Object (Initialization)

After creating web worker file we need to call (link) this file. For this, we need to create a web worker object that runs the web worker file code.

					 
        
          if(typeof(Worker) !== "undefined"){
            worker = new Worker("worker.js");
          } else {
            alert('Web worker not supported.');
          }
        
      
Receive Message From Web Worker

To receive messages from web worker we use onmessage event listener.

					 
        
          worker.onmessage = function(event){
            document.getElementById("result").innerHTML = event.data;
          }
        
      

When web worker post message via postMessage() method, the worker.onmessage event listener receive it and store it in event variable.

Terminate Web Worker

To web worker continue to execute until it is terminated by terminate() method.

					 
        
          worker.terminate();
        
      
Reuse Web Worker

When the worker is terminated, set it to undefined so that we can reuse it.

					 
        
          worker = undefined;
        
      
Complete Example Code
					 
        
          <!DOCTYPE html>
          <html>
            <head>
              <script>
                var worker;

                function startWebWorker(){
                  if(typeof(Worker) !== "undefined"){
                    if (typeof(worker) == "undefined") {
                      worker = new Worker("worker.js");
                    }
                    worker.onmessage = function(event) {
                    document.getElementById("result").innerHTML = event.data;
                    };
                  } else {
                    alert('Web worker not supported.');
                  }
                }

                function stopWebWorker() {
                  worker.terminate();
                  worker = undefined;
                }
              </script>
            </head>
            <body>
              <p>DateTime: <output id="result"></output></p>
              <button type="button" onClick="startWebWorker()">Start Worker</button>
              <button type="button" onClick="stopWebWorker()">Stop Worker</button>
            </body>
          </html>
        
      
Web workers do not execute on local file (file protocol). You need to use http or https (live server).
Alternative, you can use "VSCode" wih "Live Server" extension. Install VSCode, and open it. In extension tab search live server and install it. Now run your files via live server. Web worker works now.

How you feel about this blog:

Share this blog on:

Report Us

If you find any error in the turtorials, or want to share your suggestion/feedback, feel free to send us email at: info@lynxsia.com

Contact Us
Ads
Logo
Lynxsia IT Solutions

We are concern with various development process like website design & development, E-commerce development, Software development, Application development, SMS & Bulk SMS Provider, PWA Development, and many more..

Kotwali Road, Chhiptehri, Banda, 210001, UP, India

Copyright © 2022, Lynxsia IT Solutions, All rights reserved