Login
Your Email
Pasword
Home
Write
Trending
History
Liked
Dashboard

What is a Web Worker in HTML5?

A web worker is a JavaScript running in the background, without affecting the performance of the page.

Do you have similar website/ Product?
Show in this page just for only $2 (for a month)
Create an Ad
0/60
0/180
When executing scripts in an HTML page, the page becomes unresponsive until the script is finished. A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.
Check Web Worker Support Before creating a web worker.
if (typeof(Worker) !== "undefined")
{ // Web worker supported
 }
else
 {
 // Web Worker  not supporting.
}

Create a Web Worker File  in an external JavaScript.
var i = 0;
 function timedCount()
{
 i = i + 1; postMessage(i);
 setTimeout("timedCount()",500);
}
timedCount();

The important part of the code above is the postMessage() method - which is used to post a message back to the HTML page.
To create a Web Worker Object The following lines checks if the worker already exists:
if (typeof(w) == "undefined")
{
 w = new Worker("demo_workers.js");
}

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

o terminate a web worker, and free browser/computer resources the terminate() method is used.
w.terminate();

After  termination  reuse the code:
w = undefined;
CONTINUE READING
Web Worker
HTML5
Ayesha
Tech writer at newsandstory