HTML Web Workers

Web Workers allow JavaScript to run in the background without blocking the main user interface. They are ideal for heavy computations and long-running tasks.

On this page

HTML Web Workers API

The Web Workers API allows JavaScript to run in the background without blocking the main page.

This helps keep web pages responsive while performing CPU-intensive tasks.

What Is a Web Worker?

Normally, JavaScript runs on the main thread, which can cause the page to freeze during heavy computations.

A web worker runs in a separate thread, allowing users to continue interacting with the page.

Web workers are ideal for tasks such as data processing, calculations, and background operations.

Browser Support

The Web Workers API is supported by all modern browsers.

Check Web Worker Support

Before using web workers, always verify browser support.

 const x = document.getElementById("result");  if (typeof(Worker) !== "undefined") {   x.innerHTML = "Your browser supports Web Workers!"; } else {   x.innerHTML = "Sorry, Web Workers are not supported."; } 

Create a Web Worker File

A web worker must be defined in a separate JavaScript file.

The example below shows a simple worker that counts numbers.

 // demo_workers.js let i = 0;  function timedCount() {   i++;   postMessage(i);   setTimeout(timedCount, 500); }  timedCount(); 

The postMessage() method sends data from the worker back to the main page.

Create a Web Worker Object

Once the worker file is created, it can be started from the main script.

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

Receive Messages from the Worker

Communication between the main thread and the worker happens through messages.

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

The value sent from the worker is available in event.data.

Terminate a Web Worker

A web worker continues running until it is stopped.

Use the terminate() method to free resources.

 w.terminate(); w = undefined; 

Reuse a Web Worker

After terminating a worker and setting it to undefined, it can be restarted later.

Web Workers and the DOM

Web workers run in an isolated context.

They do not have access to:

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

This design improves performance and security by keeping background tasks separate from the UI.

HTML Web Workers Examples (5)