HTML5 Web Workers
A web worker is JavaScript that runs in the background and does not affect page performance.
What is a Web Worker?
When a script is executed in an HTML page, the page is unresponsive until the script has finished.
A web worker is JavaScript that runs in the background, independent of other scripts, and does not affect page performance. You can continue doing anything you like: clicking, selecting content, and so on, while the web worker runs in the background.
Browser support





Internet Explorer 10, Firefox, Chrome, Safari, and Opera all support web workers.
HTML5 Web Workers Example
The following example creates a simple web worker that counts in the background:
Example
Count:
Try it »
Code in the demo_workers.js file
var
i
=
0
;
function
timedCount
(
)
{
i
=
i
1
;
postMessage
(
i
)
;
setTimeout
(
"timedCount()"
,
500
)
;
}
timedCount
(
)
;
Checking Whether the Browser Supports Web Workers
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 is not supported
}
Creating a web worker file
Now, let's create our web worker in an external JavaScript.
Here, we create the counting script, which 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 more CPU-intensive tasks.
Creating a Web Worker Object
We already have the web worker file; now we need to call it from the HTML page.
The following code checks whether a worker exists; if not, 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 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 to listen for messages (even after the external script has finished) until it is terminated.
To terminate a web worker and release browser/computer resources, use the terminate() method:
w.terminate();
Complete Web Worker Example Code
We have seen the Worker code in the .js file. Below is the code for the HTML page:
Example
Try it »
Web Workers and the DOM
Because web workers are located in external files, they cannot access the following JavaScript objects:
- window object
- document object
- parent object