Web Workers

ECMAScript 2026

A browser uses a main thread to run the page’s JavaScript and respond to the user. A Web Worker can do computation separately. The page and worker exchange messages because the worker cannot directly change the page’s DOM.

On this page

Prepare the page that shows the result

The page has a paragraph for the result and a script loaded as a module. role="status" identifies an area that can announce changes to assistive technology.

How to try it Create a new folder and save the code as index.html.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Worker demo</title>
</head>
<body>
  <p id="total" role="status">Adding values…</p>
  <script type="module" src="./main.js"></script>
</body>
</html>

What to expect After the next two files are ready, the page can show the worker’s result.

Start the worker and send it values

new Worker starts another script. new URL resolves the file next to this module. postMessage sends supported data to that script. onmessage receives the reply and updates the DOM from the page. Since this is a one-time calculation, terminate() stops the worker after a reply or an error.

How to try it Save as main.js beside index.html.

const worker = new Worker(new URL("./total-worker.js", import.meta.url), { type: "module" });
const output = document.querySelector("#total");
worker.onmessage = event => {
  output.textContent = "Total: " + event.data;
  worker.terminate();
};
worker.onerror = () => {
  output.textContent = "Could not calculate the total.";
  worker.terminate();
};
worker.postMessage([12, 18, 24]);

What to expect This script sends three numbers to the worker. The last step supplies that worker.

Calculate and reply in the worker

The worker has its own global object, called self here. Its onmessage reads the copied values in event.data. The worker computes the total and posts a message back to the main page.

How to try it Save as total-worker.js beside the other two files. Serve this folder with Live Server or python -m http.server 8000 and open http://localhost:8000.

self.onmessage = event => {
  const total = event.data.reduce((sum, value) => sum + value, 0);
  self.postMessage(total);
};

What to expect The page changes to Total: 54. Change the list in main.js and reload to see the new total.

Official references