Introduction to HTML5 Web Workers with Example

HTML5 Web Workers with Example

You must noticed about the execution of JavaScript in a HTML page. Unless until the execution get finish page act like unresponsive. Some time it also hang your browser where CPU utilization is high. To overtake this problem HTML5 Introduced Web Workers. Using HTML5 web workers we can execute any number of scripts independently in background without affecting the page performance. While a script is executing inside a Web Workers, it cannot access the properties of Document Object Model (DOM).

Example of HTML5 Web Workers

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Example of HTML5 Web Worker</title>
</head>
<body>
<div>Count numbers: <output id="showResult"></output></div>
<button onclick="startWebWorker()">Start Web Worker</button>
<button onclick="stopWebWorker()">Stop Web Worker</button>

<p><strong>Note:</strong> IE 9 &amp; pervious versions don't support HTML5 Web Workers.</p>

<script type="text/javascript">
var w;

function startWebWorker() {
if(typeof(Worker) !== "undefined") {
if(typeof(w) == "undefined") {
w = new Worker("web_workers.js");
}
w.onmessage = function(event) {
document.getElementById("showResult").innerHTML = event.data;
};
} else {
document.getElementById("showResult").innerHTML = "Sorry, Please update your Browser...";
}
}

function stopWebWorker() {
w.terminate();
w = undefined;
}
</script>
</body>
</html>

How Web Workers Work?

Using new keyword to initiate a web worker we required the path of a JavaScript file. Which file contains the actual code for operations. In your application if has multiple supporting javascript files, you can import them importScripts() method. Communication between web worker and its parent page is done using the postMessage() method. postMessage() can accept either a JSON object or string as the argument. Message passed by Web Worker is accessible in main page using onmessage event. To stop web worker you can use terminate() method.

How to Create a HTML5 Web Workers File?

Refer to the above example I have the web worker file is web_workers.js. Look at the below example how I created this js file. Normally we use web workers for more CPU intensive tasks not for simple scripts.

var i = 0;
function countDown() {
    i = i + 1;
    postMessage(i);
    setTimeout("countDown()",500);
}
countDown();

Which Browsers does it Supports?

HTML5 Web Workers supported by IE 10, Chrome 4.0, Mozilla Firefox 3.5, Safari 4.0, Opera 11.5 & above versions.