HTML Web Workers API
A web worker is an external JavaScript file that runs in the background, without affecting the performance of the page.
What is a Web Worker?
When a script runs on an HTML page, the page becomes unresponsive until the script finishes. A web worker is an external JavaScript file that runs in the background, independently of other scripts, without affecting the page, so you can keep clicking and selecting while it runs. Web workers are useful for heavy code that would otherwise create long tasks and freeze the page.
Browser Support
The Web Workers API is supported in all modern browsers (from Chrome 4, Edge 10, Firefox 3.5, Safari 4, and Opera 11.5).
Web Workers API Example
A simple web worker can count numbers in the background while the page stays responsive.
Note: Web workers are not normally used for such simple scripts, but for more CPU-intensive tasks.
Check Web Worker API Support
Before using a web worker, you can quickly check support by testing typeof(Worker).
Example
Checking for Web Worker support.
Output: complete HTML page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Check Support</title>
</head>
<body>
<p id="result"></p>
<script>
const x = document.getElementById("result");
if (typeof(Worker) !== "undefined") {
x.innerHTML = "Your browser support Web Workers!";
} else {
x.innerHTML = "Sorry, your browser does not support Web Workers.";
}
</script>
</body>
</html>
Create a .js Web Worker File
A web worker lives in an external JavaScript file. Here is a script that counts, stored in demo_workers.js.
Note: The important part is the postMessage() method, which posts messages back to the HTML page.
demo_workers.js
The external worker file that counts and posts each number back.
var i = 0;
function timedCount() {
i = i + 1;
postMessage(i);
setTimeout("timedCount()", 500);
}
timedCount();
Create a Web Worker Object
Once the .js file exists, you call it from an HTML page. The code checks whether a worker already exists and, if not, creates one with new Worker("demo_workers.js"). Data is passed between the worker and the main thread with messages: both sides send with postMessage() and respond with the onmessage event handler. You add an onmessage listener to the worker object, and when the worker posts a message the listener runs, with the data available in event.data.
Terminate a Web Worker
Once created, a web worker keeps listening for messages until it is terminated. To stop it and free resources, call the terminate() method.
Reuse the Web Worker
If you set the worker variable to undefined after terminating it, you can reuse the worker code.
Full Web Worker Example
Below is the full HTML page that works with the worker file shown earlier.
Example
A complete page that starts and stops a counting web worker.
Output: complete HTML page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Full Worker</title>
</head>
<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() {
const x = document.getElementById("result");
if (typeof(Worker) !== "undefined") {
if (typeof(w) == "undefined") {
w = new Worker("demo_workers.js");
}
w.onmessage = function(event) {
x.innerHTML = event.data;
};
} else {
x.innerHTML = "Sorry! No Web Worker support.";
}
}
function stopWorker() {
w.terminate();
w = undefined;
}
</script>
</body>
</html>
Web Workers and the DOM
Because web workers live in external .js files, they cannot access the window object, the document object, or the parent object.