In a standard web page, JavaScript runs on a single "thread." This means if a script is doing heavy calculations, the page becomes frozen and unresponsive. A Web Worker solves this by running a script in the background, independent of the user interface.
A Web Worker is a JavaScript file that runs in the background. It allows you to perform heavy tasks (like processing large data sets or image manipulation) while the user continues to click, scroll, and interact with the page smoothly
Always check for browser support before initializing a worker:
if (typeof(Worker) !== "undefined") {
// Success! Web Workers are supported.
} else {
// Handle older browsers
console.log("Web Workers are not supported on this browser.");
}
Step A: Create the External Worker File
You must put the background code in a separate .js file (e.g., task.js). Inside this file, we use postMessage() to send data back to the main page.
File: task.js
let i = 0;
function count() {
i++;
// Send the result back to the main thread
postMessage(i);
setTimeout(count, 500);
}
count();
On your main HTML page, you initialize the worker and set up an onmessage listener to receive the data.
Main Page Script:
let myWorker;
function startTask() {
if (typeof(myWorker) == "undefined") {
myWorker = new Worker("task.js");
}
myWorker.onmessage = function(event) {
}
document.getElementById("result").innerHTML = event.data;
};
}
Workers consume system resources. When the task is finished, use the terminate() method to stop it and free up the browser's memory.
function stopTask() {
myWorker.terminate();
myWorker = undefined; // Clear the variable so it can be restarted
}
Because Web Workers run in a separate environment, they are isolated from the main page. They cannot access:
You can copy this into your project to see the background counter in action:
<!DOCTYPE html>
<html>
<body>
<h2> Background Task Demo </h2>
<p> Count: <strong id="result"> 0 </strong> </p>
<button onclick="startWorker()"> Start Task </button>
<button onclick="stopWorker()"> Stop Task </button>
<script>
let w;
function startWorker() {
if (typeof(Worker) !== "undefined") {
if (typeof(w) == "undefined") {
w = new Worker("demo_workers.js");
}
w.onmessage = function(event) {
document.getElementById("result").innerText = event.data;
};
}
}
function stopWorker() {
if (w) {
w.terminate();
w = undefined;
}
}
</script>
</body>
</html>
| Feature | Main Thread | Web Worker |
|---|---|---|
| UI Interaction | Yes (Handles clicks/scrolls) | No |
| DOM Access | Yes | No |
| Heavy Logic | No (Will freeze the page) | Yes (Ideal for background tasks) |
| Communication | postMessage | onmessage |