Wednesday, October 10, 2012

WebWorker in HTML5

 Hi Friends
This blog post  is because of Girish :) He enquire about Worker process and help me out to understand the concept. Thanks to Girish.

Webworker is new concept in HTML5. In earlier days when we execute scripts in HTML page , the page become unresponsive if use start clicking all over the page and script is taking time to execute.

A webworker is a javascript that runs in background ,independent of other scripts and without affecting the performance of the page. User can continue with whatever he wants, webworker works in background.

All major browser which support HTML5 will support this concept.

Before creating webwork you can use this function to check if your broswer support it or not.

function Checkwebworker()
{
if(typeof(Worker)!=="undefined")
  {
  }
else
  {
    alert('Your browser don't support webworker");
  }
}

PostMessage() method is used to post a messageback to HTML page.

you can create web worker object using below code
Worker oWorker= new Worker("javascript file name");

onmessage event listener can be used to send and receive message to the web worker.

oWorker.onmessage=function(event){
document.getElementById("txtresult").innerHTML=event.data;
};

When the webworker posts a message , the code in event listener is executed.

when webworker object is created ,it will continue to listen the messages until it is terminated.

we can use below syntax to terminate web worker process.
oWorker.terminate();

below is a simple html example of web worker process
<html>
<body>

<p>Count value: <output id="txtresult"></output></p>
<button onclick="startWorkerprocess()">Start Worker</button>
<button onclick="stopWorkerprocess()">Stop Worker</button>
<br><br>

<script>
var oWorker;

function startWorkerprocess()
{
if(typeof(Worker)!=="undefined")
{
  if(typeof(w)=="undefined")
    {
    oWorker=new Worker("demoworkers.js");
    }
  oWorker.onmessage = function (event) {
    document.getElementById("txtresult").innerHTML=event.data;
  };
}
else
{
document.getElementById("txtresult").innerHTML="Your browser does not support Web Workers.";
}
}

function stopWorkerprocess()
{
oWorker.terminate();
}
</script>

</body>
</html>