HTML5 - Web Workers

In this article you will learn about Web Workers in HTML5.

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 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 that why we need web workers. Let us take an example.

  1. <!DOCTYPEhtml>  
  2. <scriptrunat="server">  
  3.     </script>  
  4.     <htmlxmlns="http://www.w3.org/1999/xhtml">  
  5.         <headrunat="server">  
  6.             <title></title>  
  7.             <script>  
  8.                 function count()  
  9.                 {  
  10.                     var j;  
  11.                     for (var i = 0; i <= 10000000000; i = 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.                 <formid="form1" runat="server">  
  40.                     <div>  
  41.                         <divid="div1" onclick="Hello_Fun()"><span>Click Me!</span></div>  
  42.                     </div>  
  43.                     </form>  
  44.             </body>  
  45.   
  46.         </html>  
  47. </Script>
When we write above code of 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 above code we call a function (count) that make a large calculation and due to this calculation web browser become unresponsive because JavaScript have a single thread and this thread is occupied by “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 current 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 to run 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 web page window object using the “window.document” that means the Web Workers doesn’t have direct access to component of web pages such that Web Workers can’t interrupt the browser UI.

Browser Support

The following list show the version of first browser that support the Web Workers.

browser

How Web Workers Work

Initialize the url of JavaScript file

Using the Worker constructor we define the url of JavaScript file that contain the code for our program. In constructor we pass the path as parameter. The following code show a demo.
  1. var Obj_ = new Worker('Call.js');  
If application have more than one JavaScript file then we can use importScript() method in which we can pass multiple path of file separated by comma.
  1. importScripts("File1.js""File2.js");  
If any specified file doesn’t exist or worker return 404, then worker will stop to work. If file exist then Web Worker will spawn a new worker thread, which is downloaded asynchronously.

Paste the following code in “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 it’s parent page:

In 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 accept 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 with 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 use “terminate ” method.
  1. Obj_.terminate();  
Checking Browser Support:

To check whether current browser support the Web Worker or not we can use “window.Worker” property. This property return “true” if browser support Web Worker else return “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

Above example show that when we click on div at that time background color of div will change and we also get output from JavaScript code. Which show that JavaScript of “Call.js” file run on a separate file and this JavaScript code doesn’t conflict with JavaScript of web application.

Point to Considered
  • Web Worker run 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 webpage.
  • Web Workers can't access JavaScript functions from the web page.
  • Objects such as window, document and parent 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 dedicated Web Worker.
  • Shared web workers are shared across multiple web pages.
  • Web Worker can use XMLHttp request to communicate with server.

Thanks for reading the article.