HTML5 Web Workers


A web worker is JavaScript running in the background, without affecting page performance.


What is a Web Worker?

When a script is executing in an HTML page, the page is not responsive until the script is finished.

A web worker is JavaScript running in the background, independent of other scripts, without affecting page performance. You can continue doing whatever you want: clicking, selecting content, etc., while the web worker runs in the background.


Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

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 Yourself »

demo_workers.js File Code

var i=0;

function timedCount()
{
    i=i+1;
    postMessage(i);
    setTimeout("timedCount()",500);
}

timedCount();


Check if the browser supports Web Worker

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

if(typeof(Worker)!=="undefined")
{
    // 是的! Web worker 支持!
    // 一些代码.....
}
else
{
    //抱歉! Web Worker 不支持
}


Create a web worker file

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

Here, we create a counting script. 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 above code is the postMessage() method - it is used to post a message back to the HTML page.

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


Create a Web Worker object

We already have the web worker file, and now we need to call it from an HTML page.

The following code detects whether 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;
};

Terminate a Web Worker

When we create a web worker object, it will continue to listen for messages (even after the external script completes) 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 already seen the Worker code in the .js file. Below is the code for the HTML page:

Example

<!DOCTYPE html> <html> <head>  <meta charset="utf-8">  <title>Example Tutorial (example.com)</title>  </head> <body> <p>Count:<output id="result"></output></p> <button onclick="startWorker()">Start Working</button> <button onclick="stopWorker()">Stop Working</button> <p><strong>Note:</strong>Internet Explorer 9 and earlier IE 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>

Try it Yourself »


Web Workers and DOM

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

  • window object
  • document object
  • parent object
Other extensions