Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

HTML5 Web Worker

4.60/5 (4 votes)
4 Mar 2015CPOL2 min read 12.4K   164  
How to Implement HTML5 Web Worker

Introduction

An introduction of HTML5 Web Worker follwing point . It includes follwing point in detail

  1. How Web Worker work?
  2. How to Create and terminate the Web Worker
  3. How to implemente it in project etc.

Background

A JavaScript is run sequentially in single-threaded environment i.e. multiple script cannot run at time.When executing big scripts in a HTML page, then page becomes unresponsive until the script is finished.

To overcome from this situation Web Worker is suitable.It execute in the background without effecting code page performance.

Using the code

What is Web Worker: A Web Worker is a JavaScript code which running in the background, independently of other scripts and without affecting the performance of page.

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

Check Web Worker Support: Before initiating the Web Worker, It must be check whether user browser support or not.

C++
if(typeof(Worker) !== "undefined")
 {// supported
   // code to initiate the Web Worker

} 
else{
// No Web Worker support by browser.
}

Initiating a Web Workers Work.

A web Worker is initialize with an external JavaScript file. JavaScript file contains the code to be execute by browser.

C++
var worker= new Worker ("testWroker.JS");

If the specified JavaScript file exists, then browser will initiate a new worker thread, file is downloaded asynchronously path not exists at specified location, it will fail silently.

Multiple supporting file can be implemented by using importScript() method.

importScripts("TestWrokerHelper.js", "myhelper.js");

C++
importScripts("TestWrokerHelper.js", "myhelper.js");

Communication between web worker and page: The postMessage() method is used for the communication between the browser and its parent page. This method accept single argument of type string or JSON.

C++
postMessage("test Web Worker");

Message return by Web Worker is access use onmessage event on parent page. When the web worker posts a message, the onmessage event listener is executed. The data pass from the web worker is stored in event.data.

C++
WebWorker.onmessage = function(event){

document.getElementById("txtResult").innerHTML = event.data; // display test Web Worker
};

Note: Web Worker do not access following objects.

  1. The window object
  2. The document object
  3. The parent object

Handling Errors: onerror event is used to handle the error of Web Worker.

objWorker.onerror = function (event) {
         console.log(event.message, event); // event.message give the error message.
      };

Terminate a Web Worker: Web Worker can be stopped by using terminate () method.After terminate the web Worker it release the browser computer resources.

C++
objWorker.terminate();

Example :

Create a Web Worker File: It is an external JavaScript file (.JS), it contains the JavaScript code which is executed by Web Worker

var icount = 0;
function fnNumberOfExecution() {
icount = icount + 1;
postMessage(icount);  // Post a message back to the HTML page.
setTimeout("fnNumberOfExecution() ",500);}
fnNumberOfExecution ();

Create a Web Worker Object: code to initaite Web Worker by using above JS file.

Var objWorker;
if(typeof(Worker) !== "undefined"){

if(typeof(objWorker)==="undefined")
{
	objWorker= new Worker("testWorker.js");
	objWorker. onmessage=function (event)   // event listener
	{
		document.getElementById("result").innerHTML =event.data;

	};

}

}else
{alert("No Web Worker support by browser..");

}

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

Points of Interest

Learn new things and Share.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)