Curriculum
Course: HTML Basic
Login

Curriculum

HTML Basic

HTML Introduction

0/1

HTML Editors

0/1

HTML Attributes

0/1

HTML Paragraphs

0/1

HTML Formatting

0/1

HTML Comments

0/1

HTML Favicon

0/1

HTML Page Title

0/1

HTML Iframes

0/1

HTML Java Script

0/1

HTML File Paths

0/1

HTML Symbols

0/1
Text lesson

Create a Web Worker Object

The following lines check if the web worker already exists.

If it doesn’t, they create a new web worker object and execute the code from “demo_workers.js”:

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

Next, add an “onmessage” event listener to the web worker to handle messages sent and received from it.

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

When the web worker sends a message, the code inside the event listener is triggered. The data from the web worker is accessible via event.data.

Terminate a Web Worker

Once a web worker object is created, it remains active and continues to listen for messages, even after the external script has finished execution.

To stop a web worker and release browser and computer resources, use the terminate() method:

w.terminate();

Reuse the Web Worker

Once you terminate a web worker using the terminate() method, you can set the worker variable to undefined and reuse the code.

w = undefined;

Full Web Worker Example Code

We’ve already reviewed the code for the Worker in the .js file. Below is the code for the HTML page:

Example

<!DOCTYPE html>
<html>
<body>

<p>Count numbers: <output id=”result”></output></p>
<button onclick=”startWorker()”>Start Worker</button>
<button onclick=”stopWorker()”>Stop Worker</button>

<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! No Web Worker support.”;
  }
}

function stopWorker() {
  w.terminate();
  w = undefined;
}
</script>

</body>
</html>

Web Workers and the DOM

Because web workers operate in external files, they do not have access to the following JavaScript objects:

  • The window object
  • The document object
  • The parent object