HTML5 - Web Workers

Introduction 

 
JavaScript work on a single thread environment, it means we can’t run multiple scripts at the same time. JavaScript will hang your browser in a situation where CPU utilization is high. A web worker is a JavaScript running in the background, without affecting the performance of the page.
 
Firstly, we will understand why we need web workers. Let us take an example. 
  1. <!DOCTYPEhtml>      
  2. <scriptrunatscriptrunat="server">      
  3.     </script>      
  4.     <htmlxmlnshtmlxmlns="http://www.w3.org/1999/xhtml">      
  5.         <headrunatheadrunat="server">      
  6.             <title></title>      
  7.             <script>      
  8.                 function count()      
  9.                 {      
  10.                     var j;      
  11.                     for (var i = 0; i <= 10000000000; ii = i + 1)      
  12.                     {      
  13.                         j += i;      
  14.                     }      
  15.                     alert("Value of j is=" + j);      
  16.                 }      
  17.       
  18.                 function Hello_Fun()      
  19.                 {      
  20.                     alert("Hello World!");      
  21.                 }      
  22.                 count();      
  23.             </script>      
  24.             <style>      
  25.                 #div1 {      
  26.                     background-color: blueviolet;      
  27.                     height: 100px;      
  28.                     width: 150px;      
  29.                     margin-left: 50px;      
  30.                     margin-top: 30px;      
  31.                     font-size: 24px;      
  32.                     text-align: center;      
  33.                     padding-top: 50px      
  34.                 }      
  35.             </style>      
  36.             </head>      
  37.       
  38.             <body>      
  39.                 <formidformid="form1" runat="server">      
  40.                     <div>      
  41.                         <dividdivid="div1" onclick="Hello_Fun()"><span>Click Me!</span></div>      
  42.                     </div>      
  43.                     </form>      
  44.             </body>      
  45.       
  46.         </html>      
  47. </Script>    
When we write the above code of the page in browsers then it will produce the following result.
 
warning
 

Why this warning occur?

 
As we know that JavaScript is a single thread process. In the above code, we call a function (count) that makes a large calculation and due to this calculation web browser becomes unresponsive because JavaScript has a single thread and this thread is occupied by the “count” method. 
 

How to resolve this issue?

 
There are several methods likes setTimeout(), setInterval(), and xmlHTTPRequest that provide asynchronous execution of code. Asynchronous events are processed after the currently executing script yielded. The good news is that HTML5 gives us something better than these approaches. Now read about Web Worker.
 

Introduction to Web Worker

 
The Web Workers define an API to run a background script in web application. Web Workers do all the computationally expensive tasks without interrupting the user interface and typically run on separate threads. In other words, Web Workers run specific code on a separate thread from general JavaScript thread. Web Workers allow running long-running scripts that are not interrupted by scripts that respond to clicks or other user interactions. 
 

Why Web Workers doesn’t block Browser UI?

 
The reason is that Web Workers can’t access the web page window object using the “window. the document” which means the Web Workers doesn’t have direct access to a component of web pages such that Web Workers can’t interrupt the browser UI.
 

Browser Support

 
The following list shows the version of the first browser that supports Web Workers.
 
browser
 

How Did Web Workers work?

 
Initialize the URL of JavaScript file
  
Using the Worker constructor we define the URL of JavaScript file that contains the code for our program. In the constructor, we pass the path as a parameter. The following code shows a demo.
  1. var Obj_ = new Worker('Call.js');     
If the application has more than one JavaScript file then we can use importScript() method in which we can pass multiple paths of file separated by a comma.
  1. importScripts("File1.js", "File2.js");     
  1. If any specified file doesn’t exist or workers return 404, the worker will stop to work. If the file exists then Web Worker will spawn a new worker thread, which is downloaded asynchronously.
Paste the following code in the “Call.js” file.
  1. //JavaScript File Code    
  2. var j = 0;    
  3. for (var i = 0; i <= 100000000; i = i + 1)    
  4. {    
  5.     j += i;    
  6. }    
  7. postMessage(j);     
Send Data from Web Worker to its parent page:
 
In the above code, we use the postMessage() method. Once the connection link is stabilized then all communication b/w Web Browser and its parent page is performed by postMessage() method. This method only accepts a single argument.
 

Received Data at Parent Page

 
At parent page message/data is received by “onmessage” event. Depending on browser or browser version, postMessage() can accept either a string or JSON object as its single argument. The latest versions of the modern browsers support passing a JSON object.
  1. Obj_.onmessage = function (event) {    
  2. alert("Your Total Sum is= " + event.data);    
Using data property of event object we can access the message or data attached to the event.
 

Terminate the Web Worker Object

 
Once the Web Browser object is created then it is necessary to terminate it because it will continue to listen for messages even after the external script is finished until it is terminated. To terminate the object using the “terminate ” method.
  1. Obj_.terminate();     

Checking Browser Support

 
To check whether the current browser supports the Web Worker or not we can use “window.Worker” property. This property return “true” if browser support Web Worker else returns “false”.
  1. if (window.Worker)    
  2. {    
  3.     alert("Web Workers supported by Browser.");    
  4. }    
  5. else    
  6. {    
  7.     alert("OOPS! Web Workers not supported by Browser.");    
  8. }    

Handling Error

 
Using “onerror” method we can handle or write the code if any error occur in Web Method.
  1. worker.onerror = function (event) {    
  2.    alert("Oops! An Error is Occur "+event.message);    
  3. };    
Let us take a complete code.
  1. <html>    
  2.     
  3. <head>    
  4.     <title></title>    
  5.     <script>    
  6.         function Hello_Fun()    
  7.         {    
  8.             document.getElementById("div1").style.backgroundColor = "Red";    
  9.             if (window.Worker)    
  10.             {    
  11.                 if (typeof(Obj_) == "undefined")    
  12.                 {    
  13.                     var Obj_ = new Worker('Call.js');    
  14.                     Obj_.onmessage = function(event)    
  15.                     {    
  16.                         alert("Your Total Sum is= " + event.data);    
  17.                     }    
  18.                     worker.onerror = function(event)    
  19.                     {    
  20.                         alert("Oops! An Error is Occur " + event.message);    
  21.                     }    
  22.                     Obj_.terminate();    
  23.                 }    
  24.                 else    
  25.                 {    
  26.                     alert("OOPS! Web Workers not supported by Browser.");    
  27.                 }    
  28.             };    
  29.         }    
  30.     </script>    
  31.     <style>    
  32.         #div1 {    
  33.             background-color: blueviolet;    
  34.             height: 100px;    
  35.             width: 150px;    
  36.             margin-left: 50px;    
  37.             margin-top: 30px;    
  38.             font-size: 24px;    
  39.             text-align: center;    
  40.             padding-top: 50px;    
  41.             margin-left: 450px;    
  42.             margin-top: 100px;    
  43.         }    
  44.     </style>    
  45. </head>    
  46.     
  47. <body>    
  48.     <formid="form1" runat="server">    
  49.         <div>    
  50.             <divid="div1" onclick="Hello_Fun()"><span>Click Me!</span></div>    
  51.         </div>    
  52.         </form>    
  53. </body>    
  54.     
  55. </html>    
Design of web page
 
Click me
 
When we click on div then the following output will be visible.
 
run
  
The above example shows that when we click on div at that time background color of div will change and we also get output from JavaScript code. This shows that JavaScript of the “Call.js” file runs on a separate file and this JavaScript code doesn’t conflict with JavaScript of the web application.
 
 
Point to Considered
  • Web Worker runs JavaScript in the background on a separate thread.
  • Web Workers can't call alert() or confirm() functions.
  • Web Workers can't access DOM elements from the web page.
  • Web Workers can't access global variables from the webpage.
  • Web Workers can't access JavaScript functions from the web page.
  • Objects such as windows, documents, and parents can't be accessed inside the Web Worker.
  • Web Worker comes in two types Dedicated and Shared Web Worker.
  • Dedicated web workers come into existence and die along with a web page that created them. It means dedicated Web Worker can’t access across multiple web pages.
  • Web Worker object refers to a dedicated Web Worker.
  • Shared web workers are shared across multiple web pages.
  • Web Worker can use XMLHttp request to communicate with the server.

Summary

 
In this article, we learned about HTML5 - Web Workers. 
 
Thanks for reading the article.


Similar Articles