HTML Introduction | HTML5 API | Web Worker

Web Worker API

When a script runs on a web page, the page cannot respond until the running script finishes. A web worker is JavaScript that runs in the background so that scripts do not affect the performance of the web page.

In other words, web workers support multithreading for scripts. This lets users continue using the web page while long-running JavaScript work is processed at the same time.

Major browser versions that support web workers are as follows.

API ie chrome firefox safari opera
web worker 10.0 4.0 3.5 4.0 11.5

Checking Web Worker Support

Before using a web worker, first check whether the user’s browser supports it.

Syntax

if (typeof(Worker) !== "undefined") {
    // Code for web workers
} else {
    // Guidance for browsers that do not support web workers
}

Creating a Web Worker File

To check how a web worker works, create an external JavaScript file that searches for prime numbers.

Example

var n = 1;
search: while (true) {
    n += 1;
    for (var i = 2; i <= Math.sqrt(n); i += 1)
        if (n % i == 0)
            continue search;
        postMessage(n);
}

In the example above, the postMessage() method is used to pass the result to the HTML document.

Creating a Web Worker Object

Create an HTML file that loads the web worker file created above.

Example

if(typeof(webworker) == "undefined") {
    webworker = new Worker("/examples/web_worker.js");
}

The example above creates a new web worker object when the web worker file does not already exist.

Connecting to the Worker Object

You can exchange messages with a web worker file through the onmessage event listener.

Example

webworker.onmessage = function(event) {
    document.getElementById("result").innerHTML = event.data;
};

When the web worker file sends a message, the event listener in the example above runs. The information sent by the web worker file is stored in event.data.

Terminating a Web Worker Object

After a web worker object is created, it continues waiting for messages until it is terminated. To return resources to the browser or computer, you should terminate the web worker with the terminate() method.

Example

webworker.terminate();

Reusing a Web Worker Object

After a web worker object is terminated, set the web worker value to undefined so that the object can be reused.

Example

webworker = undefined;

Web Worker Example

The following example shows the web worker behavior covered above in a single example.

Example

var webworker;
function startWorker() {
    if(typeof(Worker) !== "undefined") {
        if(typeof(webworker) == "undefined") { webworker = new Worker("/examples/web_worker.js"); }
        webworker.onmessage = function(event) { document.getElementById("result").innerHTML = event.data; }; 
    }
}
function stopWorker() { 
    webworker.terminate();
    webworker = undefined;
}