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

File upload and Progress events with HTML5 XmlHttpRequest Level 2

The XmlHttpRequest Level 2 specification adds several enhancements to the XmlHttpRequest object. Last week I had blogged about cross-origin-requests and how it is different from Flash\Silverlight's approach .  With Level 2 specification one can upload the file to the server by passing the file object to the send method. In this post I'll try to explore uploading file using XmlHttpRequest 2 in conjunction with the progress events. I'll also provide a description on the new HTML5 tag -  progress which can be updated while the file is being uploaded to the server. And of course, some ColdFusion code that will show how the file is accepted and stored on the server directory.

Server sent events with HTML5 and ColdFusion

There are several ways to interact with the server apart from the traditional request\response and refresh all protocol. They are polling, long polling, Ajax and Websockets ( pusherapp ). Of all these Ajax and Websockets have been very popular. There is another way to interact with the server such that the server can send notifications to the client using Server Sent Events (SSE) . SSE is a part of HTML5 spec:  http://dev.w3.org/html5/eventsource/

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.