HTML 5 Web Workers

A web worker is JavaScript running in the background and will not affect the performance of the page.

What is Web Worker?

When a script is executed in an HTML page, the state of the page is not responsive until the script is completed.

A web worker is JavaScript running in the background, independent of other scripts, and will not affect the performance of the page. You can continue to do whatever you want: click, select content, etc., while the web worker is running in the background.

HTML5 Web Workers example

The following example creates a simple web worker that counts in the background:

Example

Novice Tutorial

count:

​ ​

Demo_workers.js file code:

var i=0;

function timedCount()
{
    i=i+1;
    postMessage(i);
    setTimeout("timedCount()",500);
}

timedCount();

Check whether the browser supports Web Worker

Before creating a web worker, check whether the user’s browser supports it:

if(typeof(Worker)!=="undefined")
{
    // Yes! Web worker support!
    // Some code...
}
else
{
    //Sorry! Web worker does not support
}

Create web worker file

Now, let’s create our web worker in an external JavaScript.

Here, we created the counting script. The script is stored in the “demo_workers.js” file:

var i=0;

function timedCount()
{
    i=i+1;
    postMessage(i);
    setTimeout("timedCount()",500);
}

timedCount();

The important part of the above code is the postMessage() method-it is used to send a message back to the HTML page.

Note: web workers are usually not used for such simple scripts, but for tasks that consume more CPU resources.

Create a Web Worker object

We already have the web worker file, and now we need to call it from the HTML page.

The following code detects whether there is a worker, if it does not exist,-it creates a new web worker object, and then runs the code in “demo_workers.js”:

if(typeof(w)=="undefined")
{
    w=new Worker("demo_workers.js");
}

Then we can generate 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 Web Worker

When we create the web worker object, it will continue to listen for messages (even after the external script completes) until it is terminated.

To terminate the web worker and release the browser/computer resources, please use the terminate() method:

w.terminate();

Complete Web Worker example code

We have already seen the Worker code in the .js file. Here is the code of the HTML page:

Example

<!DOCTYPE html>
<html>
	<head> 
		<meta charset="utf-8"> 
		<title>Novice Tutorial</title> 
	</head>
	<body>
 		<p>count: <output id="result"></output></p>
		<button onclick=" startWorker() " > Start worker </button> 
		<button onclick = " stopWorker() " > Stop worker </button> 
		<p><strong> Note: </strong> Internet Explorer 9 and earlier IE browsers Web Workers are not supported. </p> 

		<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, your browser does not support Web Workers... ";
				} 
			} 

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

Web Workers with DOM

Since web workers are located in external files, they cannot access the following JavaScript objects:

  • window object
  • document object
  • parent object