A web worker is like having a helper that works in the background while you keep using the page. Without web workers, heavy tasks can freeze your browser. With web workers, the page stays responsive.
What is a Web Worker?
When you run a complex JavaScript task, your browser can freeze. You cannot click buttons, scroll, or type while the code runs. This is bad for user experience.
A web worker solves this by running the heavy code in the background. You can keep clicking and scrolling while the worker does its job.
Web workers are useful for:
- Processing large amounts of data
- Complex calculations
- Image or video processing
- Any task that takes more than a few seconds
Browser Support
Web Workers are supported in all modern browsers:
| Feature | Chrome | Edge | Firefox | Safari | Opera |
|---|---|---|---|---|---|
| Web Workers | 4.0 | 10.0 | 3.5 | 4.0 | 11.5 |
Check if Web Workers are Supported
Before using web workers, always check if the browser supports them:
How Web Workers Work
Web workers work in four simple steps:
- Create a worker file – A separate .js file that contains the background code
- Create a worker object – In your main page, create a new Worker object pointing to that file
- Send and receive messages – Use
postMessage()andonmessageto communicate - Terminate the worker – When done, stop the worker to save resources
Simple Web Worker Example
This example counts numbers in the background. The page stays responsive while the worker runs.
Note: Since web workers require an external .js file, this example shows how the code would look. To actually run it, you would need to create the worker file on your server.
var i = 0;
function timedCount() {
i = i + 1;
postMessage(i);
setTimeout("timedCount()", 500);
}
timedCount();
This worker counts up every half second and sends the number back to the page.
<!DOCTYPE html>
<html>
<body>
<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button>
<button onclick="stopWorker()">Stop Worker</button>
<script>
let w;
function startWorker() {
if (typeof(Worker) !== "undefined") {
if (typeof(w) == "undefined") {
w = new Worker("demo_worker.js");
}
w.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data;
};
} else {
document.getElementById("result").innerHTML = "Sorry! No Web Worker support.";
}
}
function stopWorker() {
w.terminate();
w = undefined;
}
</script>
</body>
</html>
Unfortunately, web workers cannot run directly in this editor because they need external .js files. But the code above would work on a real web server.
Communication Between Page and Worker
The page and the worker communicate by sending messages back and forth:
- Worker to page: Worker uses
postMessage()to send data. Page receives it throughonmessage. - Page to worker: Page uses
worker.postMessage()to send data. Worker receives it throughonmessage.
onmessage = function(event) {
var data = event.data;
postMessage("Received: " + data);
}
worker.postMessage("Hello worker!");
worker.onmessage = function(event) {
console.log("Worker says: " + event.data);
}
Terminating a Web Worker
Web workers continue running in the background even after you close the page. To stop them and save resources, use the terminate() method:
// Stop the worker
w.terminate();
// Reset the variable so you can start a new worker later
w = undefined;
If you do not terminate a worker, it keeps running and using memory. Always terminate workers when you are done with them.
What Web Workers Cannot Do
Web workers run in isolation. They do NOT have access to:
- The
windowobject (cannot access the browser window) - The
documentobject (cannot access or change the page directly) - The DOM (cannot add or remove elements)
- Local storage or session storage directly
Workers can only communicate with the page through messages. They are designed this way for security and performance.
Real-World Uses for Web Workers
- Data processing – Sorting large arrays or filtering thousands of items
- Image editing – Applying filters or effects to large images
- Spreadsheet calculations – Recalling complex formulas in web apps
- Real-time data monitoring – Checking for updates from a server without freezing the UI
- File processing – Parsing large CSV or JSON files
- Background sync – Uploading data when the user is offline
Quick Summary
- Web workers run JavaScript in the background without freezing the page.
- Use
new Worker("file.js")to create a worker. - Use
postMessage()to send data andonmessageto receive it. - Use
terminate()to stop a worker and free resources. - Workers cannot access the DOM, window, or document objects.
- Always check if the browser supports workers with
typeof(Worker) !== "undefined". - Workers are best for heavy CPU tasks that would otherwise freeze the page.
What Just Happened? Let Me Explain
- JavaScript normally runs on one thread (a single line of code at a time). If one task takes 5 seconds, everything freezes for 5 seconds.
- Web workers create a second thread. Now two things can happen at once. The page stays responsive while the worker works.
- Workers are isolated for security. They cannot touch the page directly. They can only send messages back to the page.
- This is like having two people on a phone call. One person is the worker (doing heavy lifting), the other is the page (showing results to the user). They talk by sending messages.
- If you do not terminate a worker, it keeps running forever. Always terminate workers when they are done.
Web Workers API Reference
| Method / Property | Description |
|---|---|
new Worker(filename)
| Creates a new web worker from a .js file |
worker.postMessage(message)
| Sends a message from the page to the worker |
worker.onmessage = function(event)
| Receives messages sent from the worker |
worker.terminate()
| Stops the web worker and frees resources |
worker = undefined
| Resets the worker variable so a new one can be created |
postMessage(message) (inside worker)
| Sends a message from the worker to the page |
onmessage = function(event) (inside worker)
| Receives messages sent from the page to the worker |