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

Custom validation messages for HTML5 Input elements using the constraint validation API

HTML5 has introduced several input types such as EMAIL, URL, RANGE, SEARCH, DATE, TIME, etc,. Most of the modern browsers have implemented them and are ready to be used in a HTML document. Another exciting feature introduced in HTML5 is the form validation. Instead of writing JavaScript to validate users input, browsers can now validate it and show an appropriate message if the validation fails. The validation message is shown in line with the field for which the validation has failed. The default error message is shown when the validation fails. In this post I'll explain how these error messages can be changed.

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.

A cheat sheet of keyboard shortcuts in ColdFusion Builder

In my last post I have explained about keyboard shortcuts in ColdFusion Builder 2.0. This blog post contains a list of all shortcut keys and I have listed these keyboard shortcuts based on the categories that it falls into. Well, this post was not planned since users can easily get to know the keyboard shortcuts by navigating to the preferences (ColdFusion -> Profiles -> Keys). However, I met Joshua at Scotch on the rocks in Edinburgh and he suggested that it would be nice to have the list of keyboard shortcuts handy. So this post is for those who would like to have the list with them and refer it whenever required.


Keyboard shortcuts for inserting text:

These are the keyboard shortcuts which are used to insert some text into the editor:

CommandKeyboard shortcuts on WindowsKeyboard shortcuts on MacInsert anchor tagCTRL + T, LCMD + T, LInsert bold tagCTRL + T, BCMD + T, BInsert br tagCTRL + T, RCMD + T, RInsert cfabortCTRL + T, ACMD + T, AInsert cfdumpCTRL + T, DCMD + T, DInsert cfs…