Web Workers API
A web worker is like a helper JavaScript that works behind the scenes without slowing down the webpage.
What is a Web Worker?
When you run scripts on an HTML page, the page doesn't respond until the script completes.
A web worker is a type of JavaScript that operates in the background without interfering with other scripts, allowing the webpage to perform well. You can carry on with your activities like clicking or selecting items while the web worker runs quietly in the background.
Check Web Worker Support
Before making a web worker, make sure the user's browser can handle it.
// Yes! Web worker support!
// Some code.....
} else {
// Sorry! No Web Worker support..
}
Create a Web Worker File
Sure, let's make a web worker in a separate JavaScript file.
We made a script that counts things. The script is kept in a file named "demo_workers.js".
function timedCount() {
i ++;
postMessage(i);
setTimeout("timedCount()",500);
}
timedCount();
The key element in the code snippet is the postMessage()
method. This method is employed to send a message back to the HTML page.
Note: Usually, web workers aren't employed for basic scripts; they're reserved for tasks that require a lot of processing power.
Web Workers Example
The following example sets up a basic web worker to count numbers in the background:
Create a Web Worker Object
We have the web worker file ready. Next, we must invoke it from an HTML page.
The code below checks if there's already a worker. If there isn't, it makes a new web worker and executes the code from "demo_workers.js":
w = new Worker("demo_workers.js");
}
Next, we can exchange messages with the web worker.
Attach an "onmessage" listener to the web worker.
document.getElementById("result").innerHTML = event.data;
};
When the web worker sends a message, the code inside the event listener runs. The information from the web worker is saved in event.data.
Terminate a Web Worker
When a web worker is made, it keeps listening for messages even after the external script finishes until it gets terminated.
To stop a web worker and release browser/computer resources, utilize the terminate()
method.
Reuse the Web Worker
If you set the "worker" variable to "undefined" once it's been stopped, you can use the code again.
Web Workers and the DOM
Web workers, which are files separate from the main web page, cannot reach certain JavaScript objects.
- The window object
- The document object
- The parent object