Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

Web Workers API

A web worker is a JavaScript that runs in the background, without impacting the page’s performance.

What is a Web Worker?

When running scripts in an HTML page, the page becomes unresponsive until the script completes.

A web worker is a JavaScript that operates in the background, independently of other scripts, without slowing down the page’s performance. This allows you to continue interacting with the page—clicking, selecting, etc.—while the web worker runs.

Browser Support

The numbers in the table indicate the first browser versions that provide full support for Web Workers.

DOM 2

Web Workers Example

The example below demonstrates how to create a simple web worker that counts numbers in the background.

Example

Count numbers:

 

Check Web Worker Support

Before creating a web worker, verify if the user’s browser supports it.

if (typeof(Worker) !== “undefined”) {
  // Yes! Web worker support!
  // Some code…..
} else {
  // Sorry! No Web Worker support..
}

Create a Web Worker File

Now, let’s create our web worker in an external JavaScript file. In this case, we have a script that performs counting, and the script is stored in the “demo_workers.js” file.

let i = 0;

function timedCount() {
  i ++;
  postMessage(i);
  setTimeout(“timedCount()”,500);
}

timedCount();

The key part of the code above is the postMessage() method, which is used to send a message back to the HTML page.

Note: Web workers are typically used for more CPU-intensive tasks, rather than simple scripts like this.

Create a Web Worker Object

Now that we have the web worker file, we need to reference it from an HTML page.

 

The following code checks if the worker already exists; if not, it creates a new web worker object and runs the code from “demo_workers.js”.

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

Next, we can send and receive messages from the web worker.

Add an “onmessage” event listener to handle messages from the web worker.

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

When the web worker posts a message, the code inside the event listener is executed. The data sent from the web worker is accessible through event.data.

Terminate a Web Worker

When a web worker is created, it continues to listen for messages even after the external script has finished. To stop the worker and release resources, you can use the terminate() method.

w.terminate();

Reuse the Web Worker

After terminating the worker, if you set the worker variable to undefined, you can reuse the code by creating a new worker instance.

w = undefined;

Full Web Worker Example Code

Below is the code for the HTML page, which complements the Worker code already seen in the .js file:

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>
let w;

function startWorker() {
  if (typeof(w) == “undefined”) {
    w = new Worker(“demo_workers.js”);
  }
  w.onmessage = function(event) {
    document.getElementById(“result”).innerHTML = event.data;
  };
}

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

</body>
</html>

Web Workers and the DOM

Since 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