* * *
A web worker is a JavaScript running in the background, without affecting the performance of the page.
* * *
## What is a Web Worker?
When executing scripts in an HTML page, the page becomes unresponsive until the script has finished.
A web worker is a JavaScript running in the background, independently of other scripts, and does not affect the performance of the page. You can continue doing whatever you wishβclicking, selecting content, etc.βwhile the web worker runs in the background.
* * *
## Browser Support

{
i=i+1;
postMessage(i);
setTimeout("timedCount()",500);
}
timedCount();
* * *
## Detecting Browser Support for Web Workers
Before creating a web worker, detect whether the user's browser supports it:
if(typeof(Worker)!=="undefined"){ // Yes! Web worker support! // Some code.....}else{ //Sorry! Web Worker not supported}
* * *
## Creating a Web Worker File
Now, letβs create our web worker in an external JavaScript file.
Here, we create the counting script. This 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 code above is the postMessage() methodβit is used to send a message back to the HTML page.
**Note:** Web workers are typically not used for such simple scripts, but rather for tasks that are more CPU-intensive.
* * *
## Creating a Web Worker Object
We now have our web worker file; next, we need to invoke it from the HTML page.
The following code checks whether a worker exists, and if not, 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 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;};
* * *
## Terminating a Web Worker
After we create a web worker object, it continues listening for messages (even after the external script has finished) until it is terminated.
To terminate the web worker and release browser/computer resources, use the terminate() method:
w.terminate();
* * *
## Complete Web Worker Example Code
Weβve already seen the Worker code in the .js file. Below is the HTML page code:
## Example
Count:
Note: Web Workers are not supported in Internet Explorer 9 and earlier versions.
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; }
[Try it yourself Β»](
* * *
## Web Workers and the DOM
Since web workers reside in external files, they cannot access the following JavaScript objects:
* window object
* document object
* parent object