Skip to main content

HTML Web Workers API

The HTML Web Workers API allows you to run scripts in the background without blocking the main thread of your web application.

This can be useful for computationally intensive tasks or long-running operations that would otherwise slow down the user interface.

A web worker is a separate JavaScript file that is executed in a separate thread from the main thread of your web application.

As an example:

// create a new web worker
const worker = new Worker("worker.js");

// send a message to the worker
worker.postMessage({number: 100});

// receive a message from the worker
worker.onmessage = function (event) {
console.log(event.data);
};

// content of worker.js
onmessage = function (event) {
const number = event.data.number;
let result = 1;
for (let i = 1; i <= number; i++) {
result *= i;
}
// send the result back to the main thread
postMessage(result);
};

In this example:

  • We create a new web worker by passing the path to the worker JavaScript file to the Worker constructor.
  • We then send a message to the worker using the postMessage method, passing an object with the number property set to the number we want to calculate the factorial of.
  • The worker receives this message in its onmessage handler and calculates the factorial, sending the result back to the main thread using the postMessage method.
  • The main thread receives the result in its onmessage handler and logs it to the console.
  • The HTML Web Workers API provides a way to perform computationally intensive tasks in the background without blocking the user interface of your web application.

Check Web Worker Support

You can check if web workers are supported in the user's browser using the typeof operator to check if the Worker constructor is defined.

As an example:

if (typeof Worker !== "undefined") {
// web workers are supported
} else {
// web workers are not supported
}

In this example:

  • We use the typeof operator to check if the Worker constructor is defined.
  • If it is defined, we know that web workers are supported in the user's browser.
  • If it is not defined, we know that web workers are not supported and we should provide an alternative way to perform the task.

Create a Web Worker File

To create a web worker file, you simply create a new JavaScript file with your worker code and save it with a .js extension.

As an example:

// worker.js
onmessage = function (event) {
const message = event.data;
console.log("Worker received message:", message);
const result = message.toUpperCase();
postMessage(result);
};

In this example:

  • We define a function that will be called whenever the worker receives a message from the main thread.
  • We log the message to the console and then transform it to uppercase before sending it back to the main thread using the postMessage method.

Once you have created your worker file, you can create a new instance of the worker in your main JavaScript file using the Worker constructor and passing the path to your worker file as an argument.

As an example:

// main.js
const worker = new Worker("worker.js");

In this example:

  • We create a new instance of the Worker object and pass the path to our worker file as an argument.
  • The worker will then run in a separate thread and can communicate with the main thread using the postMessage and onmessage methods.

Create a Web Worker Object

To create a web worker object in your main JavaScript file, you can use the new Worker() constructor, passing the path to the worker file as an argument.

As an example:

const worker = new Worker("worker.js");

In this example:

  • We create a new Worker object and pass the path to the worker file, worker.js, as an argument.

Once you have created the worker object, you can send messages to the worker using the worker.postMessage() method.

As an example:

worker.postMessage("Hello, worker!");

In this example:

  • We send a message to the worker with the text "Hello, worker!".

You can also receive messages from the worker using the worker.onmessage() method.

As an example:

worker.onmessage = function (event) {
console.log("Message received from worker:", event.data);
};

In this example:

  • We define a function to be called whenever a message is received from the worker.
  • The event parameter contains the message data, which we log to the console.

Finally, to terminate the worker, you can call the worker.terminate() method.

As an example:

worker.terminate();

In this example:

  • We terminate the worker immediately after sending a message to it.
  • It's important to note that terminating a worker will immediately stop its execution and any unfinished work will be lost.
  • You should only terminate a worker when you no longer need it.

Full Web Worker Example

Example of using web workers to calculate the factorial of a number in an inline HTML document:

Editor

Loading...