English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

HTML5 Web Workers

Web workers are JavaScript running in the background, which will not affect the performance of the page.

What is Web Worker?

When executing scripts in the HTML page, the state of the page is unresponsive until the script is completed.

Web workers are JavaScript running in the background, independent of other scripts, and will not affect the performance of the page. You can continue to do anything you like: click, select content, etc., 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:

Online Example

Count:


demo-workers.js file code:

var i=0;
function timerCount()
{
i=i+1;
postMessage(i);
setTimeout("timerCount()",500);
}
timerCount();

Check if the browser supports Web Worker

Before creating a web worker, please check if the user's browser supports it:

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

Create web worker file

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

Here, we create the counting script. The script is stored in "demo"-in the "workers.js" file:

var i=0;
function timerCount()
{
    i=i+1;
    postMessage(i);
    setTimeout("timerCount()",500);
}
timerCount();

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

Note: Web workers are usually not used for such simple scripts, but for more CPU-intensive tasks.

Create 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 then runs "demo"-workers.js" code:}

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;
};

When a web worker passes a message, it will execute the code in the event listener. The data in event.data comes from event.data.

Terminate Web Worker

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

To terminate a web worker and release the browser/For computer resources, please 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:

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">-8"> 
<title>Basic Tutorial Website(oldtoolbag.com)</<title> 
</<head>
<body>
 
<p>Count: <output id="result"></output></p>
<button onclick="startWorker()">Start Work</button> 
<button onclick="stopWorker()">Stop Work</button>
 
<p><strong>Attention:</<strong>Internet Explorer 9 and earlier IE version browsers do not support Web Workers.</p>
 
<script>
var w; 
function startWorker() {
    if(typeof(Worker) !== "undefined") {
        
            -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>
Test to see ‹/›

Web Workers and DOM

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

  • window Object

  • document Object

  • parent Object