HTML Tutorial
HTML Forms
HTML Graphics
HTML Media
HTML API
HTML Web Workers API
What is a Web Worker?
While executing scripts in an HTML page, the page becomes unresponsive unless the script is completely finished.
A web worker is defined as a JavaScript that’s runs in the background, without affecting the performance of the page. The work can be continued like the : clicking, selecting things, etc., while the web worker runs in the background.
HTML Web Workers Example
The example below is used to illustrate simple web worker that count numbers in the background:
Count numbers:
Note: Internet Explorer 9 and earlier versions do not support Web Workers.
Check Web Worker Support
Before you start creating a web worker, always make sure to check whether the user’s browser supports it or not:
if (typeof(Worker) !== “undefined”) {
// Yes! Web worker support!
// Some code…..
} else {
// Sorry! No Web Worker support..
Create a Web Worker File
Create a sweb worker in an external JavaScript.
Here, we create a script that counts. 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 code above is the postMessage() method – which is used to post a message back to the HTML page.
Create a Web Worker Object
Now, once the web worker file is retrieved, you can call it from an HTML page.
The following lines checks if the worker already 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;
};
Terminate a Web Worker
After the web worker object is created, it continues to listen for messages until it is terminated.
The terminate() method is used to terminate a web worker, and free browsers or computer resources:
w.terminate();
Reuse the Web Worker
Set the worker variable to undefined, after it has been terminated, the codes can be reused:
w = undefined;
Full Web Worker Example Code
We have already seen the Worker code in the .js file. Following is the code for the HTML page:
Example
Count numbers:
Note: Internet Explorer 9 and earlier versions do not support Web Workers.
Web Workers and the DOM
As the web workers are in external files, they are unable to access the following JavaScript objects:
- The window object.
- The document object.
- The parent object.