HTML5 Web Workers


Release date:2024-02-21 Update date:2024-02-23 Editor:admin View counts:47

Label:

HTML5 Web Workers

Web worker is a JavaScript that runs in the background and does not affect the performance of the page.

What is Web Worker?

When a script is executed in a HTML page, the state of the page is unresponsive until the script is complete.

Web worker is a JavaScript that runs in the background, independent of other scripts, and does not affect the performance of the page. You can continue to do whatever you want: click, select, and so on, while web worker is running in the background.

Browser support

Internet Explorer Firefox Opera Google Chrome Safari

Internet Explorer 10, Firefox, Chrome, Safari and Opera all support Web workers.

HTML5 Web Workers instance

The following example creates a simple web worker that counts in the background:

Example

Count:

Start Worker

Stop Worker

demo_workers.js file code

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

Check whether the browser supports Web Worker

Before you create a web worker, check if the user’s browser supports it:

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

Create a web worker file

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

Here, we create a count 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 postMessage() method-it is used to return a message to the HTML page.

Note: web worker is not usually used for such simple scripts, but for tasks that consume more CPU resources.

Create a Web Worker object

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

The following code detects whether worker exists, and if not,-it creates a new web worker object and then runs the code in “demo_workers.js”:

if(typeof(w)=="undefined")
{
    w=new Worker("demo_workers.js");
}

Then we can generate and receive messages from web worker.

Add a “onmessage” event listener to web worker:

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

Terminating Web Worker

When we create the web worker object, it continues to listen to the message (even after the external script completes) until it is terminated.

To terminate web worker and release browser / computer resources, use the terminate() methods:

w.terminate();

Complete Web Worker instance code

We’ve already seen it. .js the Worker code in the file. Here is the code for the HTML page:

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Rookie Tutorial(runoob.com)</title>
</head>
<body>

<p>count: <output id="result"></output></p>
<button onclick="startWorker()">start work</button>
<button onclick="stopWorker()">stop working</button>

<p><strong>Note:</strong> Internet Explorer 9 and earlier versions of IE browsers 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

Because web worker is in an external file, they cannot access the following JavaScript objects:

  • window object

  • document object

  • parent object

Powered by TorCMS (https://github.com/bukun/TorCMS).