HTML5 - Introduction
HTML5 - New Elements
HTML5 - Removed Elements
HTML5 - Browser Check
Tag Name : webworker
Are you familiar with the browser prompt that asks if it needs to stop the script that is currently running. This happens usually when a block of script is running on the current page. Since this code runs in a synchronous manner and could affect the performance of the web page.
The HTML5 'Web Worker' feature allows a block of java script to be designated as a web worker and hence in an asynchronous manner without affecting the performance of the web page. In HTML5 a web worker code is contained with in an external .js file. As a result, a web worker will not be able to access the (page) parent object, window object and the document object. The web worker java script module communicates back to the page via the built-in 'postMessage()' method.
On the web page, the message sent by the web worker is received via the built-in 'onmessage' web worker event. Let us look at a simple web worker script that sends current time back to the web page.
timer-web-worker.js :

var spaceUsed=100;

function updateUsedSpace()
{
spaceUsed=spaceUsed+10;
postMessage(spaceUsed);
//assumption : every second there is a 10MB disk space used.
setTimeout("updateUsedSpace()",100);
}

updateUsedSpace();
web page code :

<!DOCTYPE HTML>
<html>
<head>
</head>
<body>


<p>Disk Space Used: <output id="spaceUsed"></output> MB</p>
<button onclick="startWebWorker()">Show Real Time Disk Usage Stats</button>
<button onclick="stopWebWorker()">Stop Real Time Update</button>
<br><br>

<script>
var webWorker;

function startWebWorker(){
if(typeof(Worker)!=="undefined"){
if(typeof(webWorker)=="undefined"){
webWorker=new Worker("disk-usage-web-worker.js");
}
webWorker.onmessage = function (event){
document.getElementById("spaceUsed").innerHTML=event.data;
};
}else{
document.getElementById("spaceUsed").innerHTML="Your browser does not support HTML5 Web Workers";
}
}

function stopWebWorker(){
webWorker.terminate();
}
</script>

</body>
</html>

© 2010 www.generalconnection.com. All rights reserved. | www.generalconnection.com