Over a million developers have joined DZone.

Building resposive Web applications with HTML5 Web Workers

DZone's Guide to

Building resposive Web applications with HTML5 Web Workers

· Web Dev Zone ·
Free Resource

Access over 20 APIs and mobile SDKs, up to 250k transactions free with no credit card required

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){  

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


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:


 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;  
   //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:

     <script type="text/javascript">  
       var worker = new Worker('NonRepeatedChar.js');  
                worker.onmessage = function(event){  
       function findNonRepeatedChar(){  
     <textarea id="myText" rows="10" cols="50">  
     <input type="button" value="Click" onclick="findNonRepeatedChar()">  

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.

#1 for location developers in quality, price and choice, switch to HERE.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}