HTML5 Web Workers
Web workers are JavaScript scripts running in the background, without affecting the performance of the page.
What is a Web Worker?
When a script is executed in an HTML page, the state of the page becomes unresponsive until the script is completed.
Web workers are JavaScript scripts running in the background, independent of other scripts, without affecting the performance of the page. You can continue to do whatever you want: click, select content, etc., while the web worker runs in the background.
Browser Support
Internet Explorer 10, Firefox, Chrome, Safari, and Opera support Web Workers.
HTML5 Web Workers Example
The following example creates a simple web worker that counts in the background:
Example
Count:
Start Worker
Stop Worker
var w;
function startWorker() {
if (typeof(Worker) !== "undefined") {
if (typeof(w) == "undefined") {
w = new Worker("/try/demo_source/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;
}
demo_workers.js File Code
var i = 0;
function timedCount() {
i = i + 1;
postMessage(i);
setTimeout("timedCount()", 500);
}
timedCount();
Detecting Browser Support for 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! No Web Worker support...
}
Creating a Web Worker File
Now, let's create our web worker in an external JavaScript.
Here, we create a 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 above code is the postMessage() method - it is used to send a message back to the HTML page.
Note: Web workers are not usually 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 if the worker exists, if not, it creates a new web worker object and 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
Once we have created a web worker object, it continues 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();
Complete Web Worker Example Code
We have seen the Worker code in the .js file. Here is the HTML page code:
Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>tutorialpro.org(tutorialpro.org)</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 versions do not support Web Workers.</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 and DOM
Since web workers are in external files, they do not have access to the following JavaScript objects:
- window object
- document object
- parent object