HTML5 new Worker

I love it, the HTML5 new worker is going to really help smoothing out the behavior of websites, and open new vistas. Now, we can control multiple JavaScript tasks simultaneously on the client computer.

Until now, we were confined to AJAX to allow the off-load of some of the work. AJAX allows the page displayed on the client computer to communicate with the server to off-load some work. AJAX allows the client computer to access the server database and server files. AJAX can do computation and send information to the client computer. AJAX is good, but, workers open up a new opportunity.

HTML5 Workers open the opportunity to control and use multiple JavaScript tasks on the client computer. This lowers the traffic between client and server and gives the client a new manner to eliminate interface (display) blocking that happens when a long task has to crank and complete before the display can continue communicating with the user.

To use a new Worker you:

  1. Create a separate JavaScript file that encapsulates the JavaScript task.
  2. Activate the JavaScript worker thread functionality.
  3. Start using the thread.

Here is a sample:

JavaScript Support Activity

Create a JavaScript file that encapsulates the needed task. As a sample create a file (worker.js) that has the following code:


  // JavaScript Document worker.js
  /* 
     use importScripts to include alternate  files needed JavaScript.
     No extra code will be needed for this sample. 
    importScripts("foo.js") ; 
  */
  /* For sample, let you know the thread has been spawned and 
      can be used. */
  postMessage("I'm waiting to do some work ...") ; 

  /* define the support action this thread provides */
  onmessage = function(evt) { 
      /* To pass data, you receive evt.data from the caller */
      var data = [] ;
      for (var i = 0 ; i < 150 ; i++) {
          data[i] =  [] ;
          for (j= 0 ; j < 150 ; j++) {
              data[i][j] = Math.random() ;
          } 
      }
      /* return the information to the caller */
      postMessage(data) ; 
  
      /* free up memory */
      data = null ;         
    
      /* close the thread if it is not doing any more */   
      self.close() ;        
  }

Spawning and Using the Worker

When the new worker is defined in a separate file, you can use it in your main page script by defining the normal response handling, error response handling and calling the worker. The following is how the worker handling is defined, spawned and used.


  var webworkers_support = !!window.Worker ;
  if (webworkers_support == true) {

      /* Workers are supported */ 
      if (typeof(worker) == "undefined")
          /* Spawn the worker */
          var worker = new Worker("worker.js") ; 
	  
	  worker.onmessage = function(evt) { 
              /* define what to do with results of the worker. */
              alert(evt.data) ;
	  } ;
	  
	  worker.onerror = function(err) {
              /* define what to do with errors in the worker */
	      document.write(
                 err.message + "<br/>" + 
                 err.filename + "<br/>" + 
                 err.lineno ) ;
              throw err ;
	  }
          /* Use/call the worker to do something */
	  worker.postMessage("msg") ;
 
	  /* If the main programs wants to control the termination 
             of the worker, you can use terminate ... 
          
              worker.terminate() ;	
          */

  } else {
      /* if running on a browser that does not support workers
         you will have to do something else ... sorry */ 
      document.write("<br/>Sorry! No web worker Support ...")
   }

Handling return errors

When an alternate thread has an error, the erroring thread will return an error code to the calling thread. The calling thread will have a function(err) defined to handle the error. The returning function can expect the following information returned:


   err.message, err.filename, err.lineno 

Information Passing

It should be mentioned, workers can't read any of the variables in the main site code. All data that the worker needs to be passed to that thread through the postMessage() calling the worker. Passing a simple variable works nicely in the simple case. In the complex case of multiple variables to be passed, consider using JSON data.

Passing Multiple Variables

To pass multiple variables, using JSON is good. To pass multiple variables, you might do the following:


   /* Define the passed variables using JSON */
   postMessage({ day: 2, month: 3, year: 1960 }) ;

   /* Given the function(evt) in the receiving thread, the parameters 
      can easily accessed as: */  
   evt.data.day, evt.data.month, evt.data.year

 

 

Leave a Reply