Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction 
2.
Types of Web Workers in HTML5
2.1.
Dedicated Web Worker
2.2.
Shared Web Workers 
3.
How does a Web Worker API work?
3.1.
Web Worker File Creation 
3.1.1.
Triggering Object creation
3.1.2.
Check API support and if Worker is available 
3.1.3.
Spawning a new Web Worker Object
3.2.
Web Worker Listener 
3.2.1.
Worker Receiving messages from the main page thread.
3.2.2.
Main page thread receiving messages from the Worker 
3.2.3.
Continuous event listening between Worker and Main Page
3.3.
Error Handling and Termination
3.3.1.
To handle errors.
3.3.2.
Terminate the worker  
4.
Where are Web-Workers Used?
5.
Accessible/Un-accessible Features
5.1.
Some of the Unaccessible features:
5.2.
Some of the Accessible features:
6.
Frequently asked questions
7.
Key takeaways
Last Updated: Mar 27, 2024

Web Workers API in HTML

Author aniket verma
0 upvote

Introduction 

This blog will learn about an advanced feature in HTML5, which is the Web Workers API in HTML5. Let us consider a situation when we are working on a Website that utilizes the CPU intensively. Along with that, we are performing some UI events or some queries. So what will happen in this case? 

There is a very high probability that the HTML page becomes unresponsive, and also, at the same time, the JavaScripts running in the background may cause the Browser to hang up.

It’s a very common phrase used in various articles and blogs that JAVASCRIPT runs in a ‘single-threaded environment,’ i.e., we cannot run multiple scripts simultaneously. So when a task gets over, the other will be executed by the other JavaScripts running behind.

Then, what is the solution to the above problem? In real-life scenarios, we want multiple queries running simultaneously/parallelly. So we need a robust solution.

At this juncture, we have the Web Workers API in HTML5. Now the problem of unresponsive web pages and hanging browsers get solved to a great extent.

Before moving on, it’s advised to have a basic understanding of HTML5 and Javascript.

Types of Web Workers in HTML5

Dedicated Web Worker

It is a type of web worker that can be accessed by only one script, which has spawned it. So as the parent threads, the worker thread also ends.

Shared Web Workers 

It is a shared web worker, as the name suggests. It is accessible to multiple scripts and communicates using the MessagePorts in the Web Workers API.

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:

  1. Web Worker File Creation
  2. Web Worker Listener
  3. 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:

  1. Grammar/Spell checkers
  2. To find syntactical code errors
  3. operations carried out on different images in the web page background
  4.  Update rows on a web page.
  5. Carry out the background operations.
  6. 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:

  1.  DOM: because they are not thread-safe.
  2.  Window Object: It runs in a different global space from the global space of the current window.
  3. The parent Object

Some of the Accessible features:

  1. Importing Multiple external scripts using importScripts()
  2. Can use setTimeout()/clearTimeout() methods
  3. Have access to the navigator object
  4. Have access to the geolocation object.
  5. 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 Modernizrwebworkers

 

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!

Live masterclass