A web worker is a JavaScript that runs in the background, without impacting the page’s performance.
When running scripts in an HTML page, the page becomes unresponsive until the script completes.
A web worker is a JavaScript that operates in the background, independently of other scripts, without slowing down the page’s performance. This allows you to continue interacting with the page—clicking, selecting, etc.—while the web worker runs.
The numbers in the table indicate the first browser versions that provide full support for Web Workers.
The example below demonstrates how to create a simple web worker that counts numbers in the background.
Count numbers:
|
Before creating a web worker, verify if the user’s browser supports it.
if (typeof(Worker) !== “undefined”) { // Yes! Web worker support! // Some code….. } else { // Sorry! No Web Worker support.. } |
Now, let’s create our web worker in an external JavaScript file. In this case, we have a script that performs counting, and the script is stored in the “demo_workers.js” file.
let i = 0; function timedCount() { i ++; postMessage(i); setTimeout(“timedCount()”,500); } timedCount(); |
The key part of the code above is the postMessage()
method, which is used to send a message back to the HTML page.
Note: Web workers are typically used for more CPU-intensive tasks, rather than simple scripts like this.
Now that we have the web worker file, we need to reference it from an HTML page.
The following code checks if the worker already exists; if not, it creates a new web worker object and runs the code from “demo_workers.js”.
if (typeof(w) == “undefined”) { w = new Worker(“demo_workers.js”); } |
Next, we can send and receive messages from the web worker.
Add an “onmessage” event listener to handle messages from the web worker.
w.onmessage = function(event){ document.getElementById(“result”).innerHTML = event.data; }; |
When the web worker posts a message, the code inside the event listener is executed. The data sent from the web worker is accessible through event.data.
When a web worker is created, it continues to listen for messages even after the external script has finished. To stop the worker and release resources, you can use the terminate()
method.
w.terminate(); |
After terminating the worker, if you set the worker variable to undefined
, you can reuse the code by creating a new worker instance.
w = undefined; |
Below is the code for the HTML page, which complements the Worker code already seen in the .js file:
<!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() { function stopWorker() { </body> </html> |
Since web workers operate in external files, they do not have access to the following JavaScript objects: