HTML5 Web Workers

What is a Web Worker?

When a script is executed in an HTML page, the state of the page is unresponsive until the script is complete.

The web worker is JavaScript running in the background, independent of other scripts, and does not affect the performance of the page. You can continue to do whatever you want to do: click, select content, etc., while the web worker is running in the background.

Browser support



Web workers are supported in Internet Explorer 10, Firefox, Chrome, Safari and Opera.

HTML5 Web Workers instance

The following example creates a simple web worker that counts in the background:

Run the program and try it out

Demo_workers.js file code:
Var me=0; 
function timedCount() 

    me=me+1; 
    postMessage(i); 
    setTimeout("timedCount()",500); 

timedCount();

Check if the browser supports Web Worker
Before creating a web worker, check if the user's browser supports it:
If(typeof(Worker)!=="undefined") 
   { 
// Web worker support! 
// Related code..... 
   } 
   else 
   { 
// Sorry! Web Worker.. 
   }

Create a web worker file
Now let's create our web worker in an external JavaScript.

Here we have created a counting script. The script is stored in the "demo_workers.js" file:

Var me=0;
Function timedCount()
{
Me=me+1;
postMessage(me);
setTimeout("timedCount()",500);
}
timedCount();
The important part of the above code is the postMessage() method - it is used to return a message to an HTML page.

Note : Web workers are typically not used for such simple scripts, but for tasks that are more CPU intensive.

Create a Web Worker object

We already have a web worker file, now we need to call it from the HTML page. /p>

The following code checks for the existence of a worker. If it doesn't exist, it creates a new web worker object and then runs the code in "demo_workers.js": /p>

If(typeof(w)=="undefined") 
  { 
  w=new Worker("demo_workers.js"); 
  }

Then we can get and receive messages from the web worker.

Add an "onmessage" event listener to the web worker:
W.onmessage=function(event){
document.getElementById("result").innerHTML=event.data; 
};

<p When web="" worker="" passes a message, the code in the event listener is executed. There is data from="" event.data="" in event.data="".

Terminate Web Worker
When we create a web worker object, it continues to listen for messages (even after the external script completes) until it is terminated.

To terminate the web worker and release the browser/computer resource, use the terminate() method:

W.terminate();

Complete web worker instance code

We have seen the Worker code in the .js file. Here is the code for the HTML page:


Last Updated: 2018-07-06 12:32:44 By akshay

SHARE THIS

share_facebook share_twitter share_google_plus

Please Comment Here :