Why use web workers?

JavaScript has been created to operate in a single-threaded environment, which implies several scripts cannot operate at the equivalent time.

Consider a position where we want to handle query and process large amounts of API data, manipulate the DOM, and UI events. JavaScript will drag our browser to a position where CPU consumption is high.

The Web Workers API allows for the asynchronous and independent implementation of a JavaScript file. A Web worker is basically a thread implementing a JavaScript file. Thus, we can attain multi-threading in our web applications by using web workers.

What is web worker?

Let us attempt to do intensive task with JavaScript that require heavy calculations and time-exhausting. Browser will slow down the web page and avoid the client from doing anything until the job is finished. It occurs because JavaScript code continuously operates in the foreground.

Web workers are introduced by HTML5 and these modern technology web workers are exclusively designed to do background work individually of other client-interface scripts, without changing the presentation of the page.

Unlike regular JavaScript operations, web worker doesn't disturb the client and the web page continues reactive because they are operating in the background.

Tip! The HTML5's web worker feature is supported in the whole modern web browsers like Opera, Chrome, Firefox, Safari and Internet Explorer 10 and above.

Advantages -

In the past a few years, we know all that web browsers, enhanced a lot and it’s mainly because of bunch of tasks performed on its machines, for example Chakra (Microsoft), V8 (Google).

In a single thread the JavaScript run so far and the single threaded design stops the code and UI that makes not responsive in case of operating complex script. There are a lot of methods to solve this problem -

  • Unload work to the server, but to get apps quicker fast user is preferred.
  • Use asynchronous calls, but several complex ecosystems of async calls & assurances could lead into call-back hell.
  • Leverage multi-threading. Web Workers solve this matter by giving ability of multi-threading in JavaScript.

Check Web Worker Support

Before establishing a web worker, test whether the client's browser supports it -

if (typeof(Worker) !== "undefined") { 
   // Yes! Web worker support!
   // Some code......
   } else {   
   // Sorry! No Web Worker support...
   } 

Create a Web Worker File

The web workers is required when doing a time-exhausting task. So here we are trying to produce an easy JavaScript task that counts from zero to 10,000.

Example: -

The following example establish an external JavaScript file named "tc_worker.js" and type
var i = 0;
  function addNumbers(){
  if(i < 10000){
  i = i + 1;
  postMessage(i);
  }
  setTimeout("addNumbers()", 300);
  } 
  addNumbers(); 

Note! In html5, Web workers have no entry to the DOM. That signifies we can't access to any DOM elements in the JavaScript code that we intend to operate using web workers.
Tip! postMessage() method is the worker object's is used to deliver a message (like the numbers in the above example) back to the web page from the web worker file.

Define Web Worker Object

Now that we have created our web worker folder. In this segment we are going to initiate the web worker from an HTML document that operates the code within the file named ‘tc_worker.js’ in the background and gradually shows the outcome on the web page.

Example -

In the following example, we can describe the background work with the web worker.
<!DOCTYPE html>
<html lang="en">
 <head>
   <meta charset="utf-8">
     <title>Using HTML5 Web Workers</title>
   <script>
      if(window.Worker) { 
      // Create a new web worker 
      var worker = new Worker("js/tc_worker.js");
      // Fire onMessage event handler 
      worker.onmessage = function(event) {
      document.getElementById("result-data").innerHTML = event.data;
          };
      } 
   </script> 
 </head>
 <body>
   <div id="result-data">
       <!--Received messages will be inserted here-->
   </div>
 </body> 
</html>   

Output -

Explaining Example -

In the above example, the javascript code has the following meaning

  • The statement var worker = new Worker("tc_worker.js"); generates a new web worker object, which is used to interact with the web worker.
  • It fires the onmessage event handler that accepts the code to collect messages from the web worker, When the worker mails a message.
  • The event.data element includes the message delivered from the web worker.
Note! The worker code runs are always saved in a distinct JavaScript file. This is to avoid web developer from forming the web worker code that efforts to use directly gain access to the elements on the web page or global variables.

Terminate a Web Worker

From the above, we have learned how to make worker and begin getting messages. However, we can also dismiss a running worker in the middle of the execution.

The created web worker object will continue to listen for messages (even after the external script is finished) until it is terminated.

To dismiss a web worker and free browser/computer resources, terminate() method is used.

Example -

The below example describes about how to begin and stop worker through clicking the HTML keys.

It uses the similar JavaScript file 'tc_worker.js' what we have used in the before example to calculate the numbers from zero to 10000.

<!DOCTYPE html>
<html lang="en">
  <head>
	<meta charset="utf-8">
	<title>Begin/Stop Web Worker in HTML5</title>
	<script>
	    // Set up global variable
	    var worker;
	    function startWorker() {
	   	// Initialize web worker
	   	worker = new Worker("js/tc_worker.js");
	   	// Run update function, when we get a message from worker
	   	worker.onmessage = update;
	   	// Tell worker to get started
	    worker.postMessage("start");
	     }
	     function update(event) {
	     // Update the page with current message from worker
	    document.getElementById("result-data").innerHTML = event.data;
	    }
	    function stopWorker() {
	   	// Stop the worker
	   	worker.terminate();
	  	}
	</script>
  </head>
  <body>
   		<h1>Web Worker Demo</h1>
   		<button onclick="startWorker();" type="button">Begin web worker
   		   </button>
  		<button type="button" onclick="stopWorker();">
			Stop web worker</button>
  		<div id="result-data">
   			<!--Received messages will be inserted here-->
   		</div>
  </body>
</html>

Output -

Note! Internet Explorer 9 and earlier versions do not support Web Workers.
Tip! Usage the web workers for execution only heavy-weight JavaScript tasks that do not disturb the client-interface scripts (i.e. scripts that react to additional client interactions or clicks). It's not suggested to use web workers for short tasks.

Browser Support

The following browsers and corresponding versions in the table that completely supports the Web Workers.

API Chrome Edge Firefox Safari Opera
Web Workers 4.0 10.0 3.5 4.0 11.5