What is Web worker in HTML 5?
When executing scripts in an HTML page, the page becomes unresponsive until the script is finished. Even when you want to execute the multiple scripts you need to execute it sequentially, you can not execute it paralally.
A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can interact with web page without blockage, while the web worker runs in the background.
Check Weather browser support.
following code is used to check the browser support for web worker.
if (typeof(Worker) !== "undefined") {
// Yes! Web worker support!
// Some code.....
} else {
// Sorry! No Web Worker support..
}
Create a Web Worker Object
Now that we have the web worker file, we need to call it from an HTML page.
if (typeof(w) == "undefined") {
w = new Worker("demo_workers.js");
}
above code will check if we worker exits if not it will create the web worker.
Post Message from Worker Thread
postMessage() method which is used to post a message back to the HTML page from web worker running in background.
Capture posted data
When worker post data to html page it fires onmessage event. you can handle it by adding an “onmessage” event listener to the web worker.
w.onmessage = function(event){
document.getElementById("result").innerHTML = event.data;
};
Terminate a Web Worker
When a web worker object is created, it will continue to listen for messages even after the external script is finished until it is terminated. To terminate a web worker, and free browser/computer resources, use the terminate() method:
w.terminate();
Complete Exmple
Following example will display all even numbers from the background threads.
///////// JS Code to execute in background //////////////////
/* background work */
var num=0;
function evennum()
{
num +=2;
postMessage(num);
setTimeout(evennum,100);
}
evennum();
// HTML Code
<html>
<head>
<title> Web worker </title>
</head>
<body>
No: <span id="sp"></span> <br>
<input type="button" value="Start" onclick="estart()"/>
<input type="button" value="Stop" onclick="estop()"/>
<script type="text/javascript">
var w;
function estop()
{
if(typeof(w)!="undefined")
{
w.terminate();
w=undefined;
}
}
function estart()
{
if(typeof(Worker)!="undefined")
{
if(typeof(w)=="undefined")
{
w =new Worker("even.js");
// alert("Worker Created!");
}
w.onmessage=function(event) // event parameter will get you data.
{
// alert(event.data);
document.getElementById("sp").innerText = event.data;
}
}
else
{
alert("Your browser do not support web worker");
}
}
</script>
</body>
</html>