HTML Web Workers


Web Workers give your website a way to run JavaScript in the background without blocking the main page. Normally, JavaScript runs on a single thread, which means long tasks can freeze the page, slow down animations or delay user interactions. With Web Workers, you can move heavy work to a separate thread. The main page stays smooth, and the worker quietly handles calculations, data processing or background tasks. This chapter explains what Web Workers are, how they work, how to create and communicate with them and where they are useful.

What Are Web Workers?

A Web Worker is a separate JavaScript file that runs outside the main browser thread. You create a worker and send messages to it. The worker runs its code independently and can send messages back when it is done. This approach helps keep the interface responsive. Even if a worker takes several seconds to finish, the user can still scroll, type, click and move around the page.

Web Workers don’t have access to the DOM. They cannot change elements or read HTML directly. Their main job is to handle background logic.

When Should You Use Web Workers?

Web Workers are useful when your website needs to process a lot of data or run long operations. Some examples include:

  • complex calculations

  • filtering or sorting large data sets

  • image processing

  • file parsing

  • encryption tasks

  • handling real-time data

  • background timers

  • tasks that should not block the user interface

Whenever you notice the page freezing during a task, moving that task to a worker is usually a good solution.

How Web Workers Work

The main script creates a worker using the Worker constructor.
The worker runs its own JavaScript file.
The main script and worker talk by sending messages.

The communication is done through postMessage() and onmessage.

Main script:

  • postMessage → send data to worker

  • onmessage → receive data from worker

Worker script:

  • postMessage → send data back

  • onmessage → receive data from main script

This message-based system keeps the two parts separate but connected.

Creating Your First Web Worker

A Web Worker requires two files:

  • the main JavaScript file

  • the worker JavaScript file

Step 1: Create the worker file

Create a file named worker.js.

// worker.js
onmessage = function(e) {
    let num = e.data;
    let result = num * num;
    postMessage(result);
}

This worker receives a number, squares it and sends the result back.

Step 2: Use the worker in the main script

Create your script.js.

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

worker.onmessage = function(e) {
    console.log("Result from worker: " + e.data);
};

worker.postMessage(7);

When you open the page, the worker calculates 7 × 7 and returns 49.

Using Web Workers with HTML

You need to link the main script inside your HTML file.

<!DOCTYPE html>
<html>
<body>

<h2>Web Worker Example</h2>

<script src="script.js"></script>
</body>
</html>

The worker runs in the background as soon as you send a message.

A Real Example: Heavy Calculation Without Blocking

Imagine you want to calculate the sum of numbers from 1 to 100 million. Doing this directly on the main thread will freeze the page.

worker.js

onmessage = function() {
    let total = 0;
    for (let i = 1; i <= 100000000; i++) {
        total += i;
    }
    postMessage(total);
}

script.js

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

worker.onmessage = function(e) {
    console.log("Total: " + e.data);
};

console.log("Worker started…");
worker.postMessage("start");

Even though the calculation is heavy, the browser stays responsive.

Sending Complex Data to Web Workers

Workers can handle:

  • numbers

  • strings

  • arrays

  • objects

  • JSON

  • structured data

Example:

main script

worker.postMessage({ name: "Anita", age: 20 });

worker file

onmessage = function(e) {
    let user = e.data;
    postMessage("Hello " + user.name);
}

Web Workers Cannot Access the DOM

Workers do not interact with the DOM. They cannot:

  • read elements

  • change text

  • update styles

This limitation keeps them safe and separate.

However, they can send data back to the main script, and the main script updates the DOM.

Example:

worker.onmessage = function(e) {
    document.getElementById("output").textContent = e.data;
};

The worker sends the data, and the main script handles the interface.

Stopping a Worker

If a worker is no longer needed, you can stop it.

From the main script

worker.terminate();

From inside the worker

close();

Stopping workers helps save memory and improves performance.

Error Handling in Web Workers

Workers have an onerror event that catches issues.

Example:

worker.onerror = function(e) {
    console.log("Error: " + e.message);
};

This is useful when your worker handles complex logic.

Example: Sorting a Large Array in Background

Sorting large arrays can slow down a page. A worker can handle it smoothly.

worker.js

onmessage = function(e) {
    let arr = e.data;
    arr.sort((a, b) => a - b);
    postMessage(arr);
}

script.js

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

worker.onmessage = function(e) {
    console.log("Sorted array:", e.data);
};

let numbers = [];
for (let i = 0; i < 500000; i++) {
    numbers.push(Math.random());
}

worker.postMessage(numbers);

The sorting happens in the background while the UI stays responsive.

Example: Live Timer Using Web Worker

Workers are perfect for long timers because they don’t pause when the page is busy.

worker.js

setInterval(function() {
    postMessage(new Date().toLocaleTimeString());
}, 1000);

script.js

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

worker.onmessage = function(e) {
    document.getElementById("clock").textContent = e.data;
};

Even during heavy operations, the timer keeps running smoothly.

When You Should Avoid Using Web Workers

Workers are powerful, but not always necessary. Avoid using them for:

  • small tasks

  • DOM-related operations

  • server-side tasks

  • libraries that require DOM access

Workers are best only for long-running or heavy tasks.

Summary of HTML Web Workers

Web Workers allow websites to run JavaScript in the background without blocking the main thread. They are ideal for heavy calculations, sorting, timers, file processing or anything that can slow down the UI. Workers communicate through messages and stay separate from the DOM. You learned how to create workers, send and receive data, stop them and use them in real examples. With Web Workers, you can build fast, smooth and interactive pages that stay responsive even under load.


Practice Questions

Q1. Create a Web Worker that calculates the sum of numbers from 1 to 1,000,000 without blocking UI.

Q2. Send a message from main script to worker and display the response.

Q3. Terminate the Web Worker after the task is completed.

Q4. Create a worker to perform factorial calculation of a given number.

Q5. Implement error handling in Web Worker using onerror.

Q6. Pass an array to the worker and receive the squared values array.

Q7. Create multiple workers to run parallel computations.

Q8. Use worker.terminate() to stop workers on button click.

Q9. Use postMessage() to send complex data objects between main script and worker.

Q10. Demonstrate how Web Workers improve UI responsiveness by comparing with synchronous code.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top