How does a Web Worker API work?
A Web Worker API is a relatively heavy-weight JavaScript running in the background in a separate thread without hampering the responsiveness of the web page. All the events can smoothly run without interrupting other tasks.
NOTE: These threads give us smooth performance but cannot be used for large numbers.
Working of a WebWorker involves 3 steps:
- Web Worker File Creation
- Web Worker Listener
- Error handling and Termination
We will discuss each step in detail.
Web Worker File Creation
First, some events should trigger the worker file to run in the background and execute the script.
For example: say, we have a button, and clicking it causes the script to run, so we must create the button object first.
Triggering Object creation
Once the button is clicked and the script is triggered, we need that function startWorker() to start executing the script. Hence our next step would be to check if this API functionality is present in your browser or not.
Check API support and if Worker is available
To check if the browser has support web worker
The other way to check is
Then if the browser supports Web Workers API, we need to check if there is any worker object already present. If not present, we will create a new worker object.
Spawning a new Web Worker Object
A new web worker object is created, which will execute the corresponding JavaScript file.
Web Worker Listener
Communication happens between the main page thread to the worker thread and vice-versa. So, there are 2 ‘.js’ scripts run, one for the main page and another for the worker.
Worker Receiving messages from the main page thread.
So what will happen is when the button is clicked, and the worker thread is spawned, and the onmessage event is triggered, which executes the code. (A sample code has been shown below).
rom worker!”);
Main page thread receiving messages from the Worker
If a worker thread listens to the message sent by the main page thread once, the web worker thread will now send the message to the main page thread, and the main page will receive the message.
rom main!”);
Continuous event listening between Worker and Main Page
This can be done by setting a time out of some small-time interval after which the messages can be sent continuously, one after the other.
Source: link
Have you ever encountered a media player running on your web page when you are watching a movie or a video clip till the time you want to watch and then when you want to close it you terminate it manually?
In the background, this continuous communication between the worker and the main page is going on.
Error Handling and Termination
To handle errors.
To trace any exceptions, we can write the following code in an HTML script.
Terminate the worker
If we want to stop the execution of the worker script, we will call the terminate() function in the main thread that free all resources of the browser.
If we want to terminate the worker’s thread, we can simply call the close() function.
In the case of the terminate() function, it doesn’t give time to pending operations to complete and destroy the web-worker thread abruptly.
In the case of the close() function, all tasks present in the event queue are dropped, and the web worker thread is destroyed.
If you notice, the communication between the Worker and Main page Thread is happening using the postMessage() function. This function is present as an internal method in the Worker’s interface. It accepts a single parameter which is a Javascript object. At one time, a single object is sent. To send multiple objects, we should pass an array of objects.
These objects are handled by the SCA, i.e., Structured Clone Algorithm, and as per HTML5, it is used to copy complex JavaScript objects. So the data sent is sent by cloning it rather than passing it by reference using the algorithm. Hence SCA is important to understand. Also, objects are handled in different dedicated spaces for both the main page and worker threads. Generally, in most browsers, JSON encoding is used to implement it.
Where are Web-Workers Used?
Web workers are a relatively new concept, and thus, we find few uses in actual real-life examples, but some of the cases where it’s used or can be used are as follows:
- Grammar/Spell checkers
- To find syntactical code errors
- operations carried out on different images in the web page background
- Update rows on a web page.
- Carry out the background operations.
- Audio-video operations and data processing
Accessible/Un-accessible Features
So as web-worker API is used to introduce the concept of multi-threading, there are a few features/ javascript objects accessible by the Web Workers API in HTML, while others are not.
Some of the Unaccessible features:
- DOM: because they are not thread-safe.
- Window Object: It runs in a different global space from the global space of the current window.
- The parent Object
Some of the Accessible features:
- Importing Multiple external scripts using importScripts()
- Can use setTimeout()/clearTimeout() methods
- Have access to the navigator object
- Have access to the geolocation object.
- XMLHttpRequest for network I/O
Frequently asked questions
Question) What are the different ways to check if Web Workers API is supported?
Answer) There are 2 ways to check, First by checking Modernizr. webworkers
returns true, or we can check it using the typeof function, i.e., typeof(w) == “undefined” returns true.
Question) What is Web Workers API?
Answer) A Web Worker API is a relatively heavy-weight JavaScript running in the background in a separate thread without hampering the responsiveness of the web page, which performs a CPU-intensive task.
Question) Why is the Web Worker API useful?
Answer) A Web Worker API is useful because it introduces the concept of multithreading in Javascript which was considered to be a language that runs in a single-thread environment.
Key takeaways
In a nutshell, in this blog, we covered the topic of Web Workers API in HTML in depth. We touched on various topics like what Web Workers API is all about and its types, working, and understood it using a sample code. We also discussed its uses and what can be done and what can’t be done.
I hope that you all could gain in-depth knowledge about the Web-Workers API in HTML and understand the topic clearly. If you want to learn more exciting stuff, you can enroll in our top-tier courses taught by the best faculty to unleash the potential of learning.
Happy Leaning Ninja!