HTML5 Web Workers
What is a Web Worker?
When executing contents in a HTML page, the page winds up plainly lethargic until the point that the content is done.
A web laborer is a JavaScript that keeps running out of sight, freely of different contents, without influencing the execution of the page. You can keep on doing whatever you need: clicking, choosing things, and so on., while the web specialist keeps running out of sight.
Browser Support
Check Web Worker Support
Before making a web laborer, check whether the client's program underpins it:
if (typeof(Worker) !== "undefined") {
// Yes! Web worker support! // Some code..... } else {
// Sorry! No Web Worker support.. }
// Yes! Web worker support! // Some code..... } else {
// Sorry! No Web Worker support.. }
Create a Web Worker File
var i = 0;
function timedCount() {
i = i + 1;
postMessage(i);
setTimeout("timedCount()",500);
}
timedCount();
function timedCount() {
i = i + 1;
postMessage(i);
setTimeout("timedCount()",500);
}
timedCount();
Create a Web Worker Object
if (typeof(w) == "undefined") {
w = new Worker("demo_workers.js");
}
Then we can send 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;
};
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();
Reuse the Web Worker
w = undefined;
Full Web Worker Example Code
Example
<!DOCTYPE html>
<html>
<body>
<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button>
<button onclick="stopWorker()">Stop Worker</button>
<script>
var w;
function startWorker()
{
if(typeof(Worker) !== "undefined")
{
if(typeof(w) == "undefined") {
w = new Worker("demo_workers.js");
}
w.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data;
};
}
else
{
document.getElementById("result").innerHTML = "Sorry! No Web Worker support.";
}
}
function stopWorker()
{
w.terminate();
w = undefined;
}
</script>
</body>
</html>
Wright © bestwebdesign and Graphics design
0 comments:
Post a Comment