HTML 5 Web Worker

What is Web Worker

 
A Web Worker is a JavaScript code that runs in the background, independently of other scripts and without affecting the performance of the page.
 
A JavaScript is run sequentially in a single-threaded environment, in other words, multiple scripts cannot run at the same time.
 
When executing large scripts in an HTML page, the page can become unresponsive until the script is finished.
 
For example a big loop:
  1. for (var ic = 0; ic <= 10000000000; ic ++){   
  2.    var j = i;  
  3. }  
To overcome that problem a Web Worker is suitable.
 
It executes in the background without affecting the code page's performance.
 
Browser Support 
  1. Chrome 4.0 and above
  2. IE 10 and above
  3. Firefox 3.5 and above
  4. Safari 4.0 and above
  5. Opera 11.5 and above.
How Web Workers Work
 
A Web Worker is initialized with an external JavaScript file. The JavaScript file contains the code to be executed by the browser.
  1. Var worker= new Worker (“testWroker.JS”);  
If the specified JavaScript file exists then the browser will initiate a new worker thread, the file is downloaded asynchronously but if the path does not exist at the specified location then it will fail silently.
 
Multiple supporting files can be implemented using the importScript() method.
  1. importScripts("TestWrokerHelper.js""myhelper.js");   
Check Web Worker Support: Before initiating the Web Worker, It must check whether or not the user's browser supports it.
 
The following is the syntax to check the browser's support of Web Workers.
  1. if(typeof(Worker) !== "undefined")   
  2. {  
  3.    // supported  
  4.    // code to initiate the Web Worker  
  5. }   
  6. else   
  7. {  
  8.    // No Web Worker support by a browser.  
  9. }  
Communication between the web worker and page: The postMessage() method is used for the communication between the browser and its parent page. This method accepts a single argument of type string or JSON.
 
For example:
  1. postMessage(“test Web Worker”);  
A message returned by Web Worker is accessed using an onmessage event on the parent page. When the web worker posts a message, the onmessage event listener is executed. The data passes from the web worker then is stored in event.data.
 
For example:
  1. WebWorker.onmessage = function(event)  
  2. {  
  3.    document.getElementById("txtResult").innerHTML = event.data; // display test Web Worker  
  4. };  
Note: a Web Worker does not access the following objects.
  1. The window object
  2. The document object
  3. The parent object
Create a Web Worker Object: Use the preceding description code to initiate the Web Worker as in the following.
  1. if(typeof(Worker) !== "undefined")   
  2. {  
  3.     if(typeof(objWorker)===”undefined”)  
  4.     {  
  5.        objWorker= new Worker(“testWorker.js”);   
  6.        objWorker. onmessage=function (event)   // event listener  
  7.       {     
  8.          document.getElementById("result").innerHTML = event.data;  
  9.   
  10.       };  
  11.    }  
  12. }   
  13. else {  
  14.     alert(“No Web Worker support by browser..”);  
  15. }  
Web Worker File: It is an external JavaScript file (.JS) that contains the JavaScript code to be executed by the Web Worker.
 
For example:
  1. var icount = 0;  
  2.   
  3. function fnNumberOfExecution() {  
  4.    icount = icount + 1;  
  5.    postMessage(icount); // Post a message back to the HTML page.  
  6.    setTimeout("fnNumberOfExecution() ",500);  
  7. }  
  8.   
  9. fnNumberOfExecution ();  
Terminate a Web Worker: a Web Worker can be stopped using the terminate() method. After terminating the Web Worker releases the browser computer resources.
 
For example:
  1. objWorker.terminate();   
  2. Handling Errors: onerror event is used to handle the error of Web Worker.  
  3. objWorker.onerror = function (event) {  
  4.    console.log(event.message, event); // event.message give the error message.  
  5. };  

Conclusion

 
Web Worker is a very important feature of HTML5. It is used to perform a task asynchronously. You can implement it for heavy calculation logic on the client browser and to execute code for a digital clock and so on.