JavaScript Web Worker API
JavaScript Basics

JavaScript Web Worker API

Web Workers API

A web worker is a JavaScript script that runs in the background without affecting the performance of the web page.

What is a Web Worker?

When executing scripts in an HTML page, the page becomes unresponsive until the script finishes. A web worker runs independently in the background, allowing the page to remain responsive. You can continue interacting with the page (clicking, selecting, etc.) while the web worker runs.

Browser Support

The table below shows the first browser versions that fully support Web Workers:

Chrome

IE

Firefox

Safari

Opera

4

10

3.5

4

11.5

Jan 2010

Sep 2012

Jun 2009

Jun 2009

Jun 2011

Web Workers Example

The example below creates a simple web worker that counts numbers in the background.

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

Check Web Worker Support

Before creating a web worker, check 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

Create a script that counts numbers. Save it in a file named "demo_workers.js":

et i = 0;function timedCount() {  i++;  postMessage(i);  setTimeout(timedCount, 500);}timedCount();

The important part of the code is the postMessage() method, which posts a message back to the HTML page. Web workers are typically used for more CPU-intensive tasks.

Create a Web Worker Object

Now that we have the web worker file, call it from an HTML page. Check if the worker already exists; if not, create a new web worker object and run the code in "demo_workers.js":

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

Send and receive messages from the web worker by adding an onmessage event listener:

w.onmessage = function(event) {

  document.getElementById("result").innerHTML = event.data;

};

When the web worker posts a message, the code within the event listener is executed. The data from the web worker is stored in event.data.

Terminate a Web Worker

To terminate a web worker and free up browser/computer resources, use the terminate() method:

w.terminate();

Reuse the Web Worker

To reuse the web worker code after it has been terminated, set the worker variable to undefined:

w = undefined;

Full Web Worker Example Code

The worker code in the "demo_workers.js" file has already been shown. 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>
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() {
  if (w) {
    w.terminate();
    w = undefined;
  }
}
</script>


</body>
</html>


Web Workers and the DOM

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

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

Take a look into your desired course