Skip to main content

Building resposive Web applications with HTML5 Web Workers

One of the key aspects of building web applications that deliver great user experience is to build applications that are highly responsive. Browser vendors are trying to improve the speed of their JavaScript engines and are enabling the web applications to perform well. Since JavaScript was introduced, there has been no way to execute the code outside of the browser UI thread i.e. it has remained single threaded. The Web Workers API introduced in HTML5 enables web applications to run scripts in the background, independent of the UI thread.

The performance of a web application can be greatly improved by using Web Workers since each worker would spawn its own thread. These threads can be used to perform computationally intensive tasks in the background without affecting the performance of the entire application.


Spawning a Worker:

The Worker() constructor is used to spawn a new worker thread. Since workers run in an isolated thread, a separate file containing the code(.js file) is created. The URI of the file is then passed as an argument to the Worker() constructor:

 var worker = new Worker('myWorker.js');  

If the file 'myWorker.js' is found, then the same would be downloaded asynchronously and a Worker thread would be spawned. To receive notifications from the Worker, the onmessage event handler can be defined:

 worker.onmessage = function(event){  
      alert(event.data);  
 }  

The Worker thread can be started using the postMessage() method:

 worker.postMessage('Data');  

The worker would handle the message received from the main page by defining a onmessage() method:

 onmessage = function(event) {  
   postMessage('Received message ' + event.data);  
 }  

The message events data attribute would contain the data passed to it from the main page. The worker can send data back to its calling thread by using the postMessage() method.

Worker Example:

As mentioned earlier, Workers can be used to perform computationally intensive tasks independently. Say if the server returns a JSON string to the client and parsing the same would take say 500ms, then performing this operation inside a Worker would make the application more responsive. I was working on an algorithm for finding the first non repeated character in a paragraph or in the user provided text (a good interview question right?). In this algorithm one has to build a hash table and insert entries for each character scanned. If the character is already present in the hash table then update its value to indicate that it appears more than once. Here is the worker code:

NonRepeatedChar.js
 onmessage = function(event){  
   //event.data contains the text in which the non-repeated character is to be found       
   var postData = event.data;
  
   //array to insert the scanned character  
   var array = {};  
   var key = {};  
   var j = 0; 
 
   //set the found flag to false  
   var found = false; 
 
   //for each character see if it is already present in the array  
   for (i = 0; i < postData.length; i++) {  
     if (postData[i] != ' ') {  
       //if the character is not present in the array, insert it into the array       
       if (!array[postData[i]]) {  
         array[postData[i]] = "Seen Once";  
         key[j++] = postData[i];  
       }  
       else {  
         //if the character appears more than once update it here  
         array[postData[i]] = "More than once";  
       }  
     }  
   }
  
   //find the first character that contains the text 'Seen Once'       
   for (i = 0; i < j; i++) {  
     if (array[key[i]] == "Seen Once") {  
       //post the result to the caller thread and break from the loop  
       postMessage("First non repeated character is " + key[i]);  
       found = true;  
       break;  
     }  
   }
  
   //if there are no non repeated characters then send a message 'Not found'  
   if (!found) {  
     postMessage("Not found");  
   }  
 }  

The main page that invokes the worker:

index.html
 <!DOCTYPE HTML>  
 <html>  
   <head>  
     <script type="text/javascript">  
       var worker = new Worker('NonRepeatedChar.js');  
                worker.onmessage = function(event){  
                     alert(event.data);  
       }  
       function findNonRepeatedChar(){  
                  worker.postMessage(document.getElementById('myText').value);  
       }        
     </script>  
   </head>  
   <body>  
     <textarea id="myText" rows="10" cols="50">  
     </textarea>  
     <input type="button" value="Click" onclick="findNonRepeatedChar()">  
   </body>  
 </html>  


A few limitations: 

Since Workers are not bound to the UI thread, they do not have access to the DOM elements defined in the calling page. Each worker thread has its own global environment and access to a limited set of JavaScript features:
  • The navigator object.
  • The location object.
  • The XmlHttpRequest object.
  • Methods - setTimeOut(), setInterval() and clearTimeOut(), clearInterval().
  • importing scripts using the method importScripts()
  • Spawning other worker threads.
Reference:

Comments

Popular posts from this blog

Adding beforeRender and afterRender functions to a Backbone View

I was working on a Backbone application that updated the DOM when a response was received from the server. In a Backbone View, the initialize method would perform some operations and then call the render method to update the view. This worked fine, however there was scenario where in I wanted to perform some tasks before and after rendering the view. This can be considered as firing an event before and after the function had completed its execution. I found a very simple way to do this with Underscore's wrap method.

De-obfuscating javascript code in Chrome Developer Tools

I had blogged about JavaScript debugging with Chrome Developer Tools  some time back, wherein I have explained how these developer tools can help in debugging javascript code. Today Google Chrome 12 was released and my Chrome browser was updated to this version. As with every release, there have been some improvements made on performance, usability etc,. One feature that stood out for me is the ability to De-obfuscate the javascript code. What is Minification? Minification is the process of removing unnecessary characters such as white spaces, comments, new lines from the source code. These otherwise would be added to make the code more readable. Minifying the source code helps in reducing the file size and thereby reducing the time taken to download the file. This is the reason why most of the popular javascript libraries such as jQuery are minified. A minified jQuery file is of 31 KB in size where as an uncompressed one is about 229 KB. Unfortunately, debugging minified javascript f

On GraphQL and building an application using React Apollo

When I visualize building an application, I would think of using React and Redux on the front-end which talks to a set of RESTful services built with Node and Hapi (or Express). However, over a period of time, I've realized that this approach does not scale well when you add new features to the front-end. For example, consider a page that displays user information along with courses that a user has enrolled in. At a later point, you decide to add a section that displays popular book titles that one can view and purchase. If every entity is considered as a microservice then to get data from three different microservices would require three http  requests to be sent by the front-end app. The performance of the app would degrade with the increase in the number of http requests. I read about GraphQL and knew that it is an ideal way of building an app and I need not look forward to anything else. The GraphQL layer can be viewed as a facade which sits on top of your RESTful services o