Wednesday, October 3rd, 2007

Optimized Speedy Ajax Code

Category: Ajax, JavaScript, Tip

<>p>Dustin Diaz has revisited his seven JavaScript techniques and has updated his XHR-getting-function to be faster, using the Lazy Function Definition Pattern, which ends up looking like:

javascript
< view plain text >
  1. var asyncRequest = function() {
  2.   function handleReadyState(o, callback) {
  3.     if (o && o.readyState == 4 && o.status == 200) {
  4.       if (callback) {
  5.         callback(o);
  6.       }
  7.     }
  8.   }
  9.   var getXHR = function() {
  10.     var http;
  11.     try {
  12.       http = new XMLHttpRequest;
  13.         getXHR = function() {
  14.           return new XMLHttpRequest;
  15.         };
  16.     }
  17.     catch(e) {
  18.       var msxml = [
  19.         ‘MSXML2.XMLHTTP.3.0′,
  20.         ‘MSXML2.XMLHTTP’,
  21.         ‘Microsoft.XMLHTTP’
  22.       ];
  23.       for (var i=0, len = msxml.length; i < len; ++i) {
  24.         try {
  25.           http = new ActiveXObject(msxml[i]);
  26.           getXHR = function() {
  27.             return new ActiveXObject(msxml[i]);
  28.           };
  29.           break;
  30.         }
  31.         catch(e) {}
  32.       }
  33.     }
  34.     return http;
  35.   };
  36.   return function(method, uri, callback, postData) {
  37.     var http = getXHR();
  38.     http.open(method, uri, true);
  39.     handleReadyState(http, callback);
  40.     http.send(postData || null);
  41.     return http;
  42.   };
  43. }();

Related Content:

  • Optimizing SAP on the WAN
    WAN optimization to speed application suites brings great benefits for any enterprise. And like most organizations,
  • Web services, AJAX loom for developers
    The rise of Web services marks a shift in focus to AJAX and client-side development. Microsoft and others will make sure developers don't have to...
  • Web services, AJAX loom for developers
    The rise of Web services marks a shift in focus to AJAX and client-side development. Microsoft and others will make sure developers don't have to...
  • Web services, AJAX loom for developers
    The rise of Web services marks a shift in focus to AJAX and client-side development. Microsoft and others will make sure developers don't have to...
  • Ajax CRUD with Struts2 and Tibco GI
    In this article you will learn how to create a new Ajax RIA front end to an existing Apache Struts2 .jsp application using TIBCO General Interface...

Posted by Dion Almaer at 8:53 am
10 Comments

+++--
3.9 rating from 36 votes

10 Comments »

Comments feed TrackBack URI

Useless there is little overhead in creating the correct XHR and loading the data over HTTP. There is much more effective result in optimizing the parsing of JSON / XML / etc.

Comment by TimD — October 3, 2007

Ignoring the lazy pattern for a minute, why can’t the XHR object be retrieved with simply:

if (window.XMLHttpRequest)
return new window.XMLHttpRequest();
else if (window.ActiveXObject)
return new ActiveXObject(“Microsoft.XMLHTTP”);

This what I have used for a long time without any problems. I don’t understand why frameworks must use a try/catch (try/catchs are usually not very fast, and very annoying with Firebug). And why the different ActiveXObjects, the MS specs seem to make it clear that you don’t need to do that (the code above should always resolve to the latest version)? Is this just case of code that has been copied time and time again without question?

Comment by Kris Zyp — October 3, 2007

In fact, try catch blocks have been shown to be extremely slow on certain browsers (the iPhone’s version of Safari for example).

Comment by Anonymous — October 3, 2007

Neglecting the try/catch and micro-optimization accusations for a moment, I started with a similar chunk of code copied from Dojo (dojo/src/hostenv_browser.js) and applied the lazy function pattern as well, except that I managed to refactor some of the logic by using an array of functions.

https://cixar.com/tracs/javascript/browser/trunk/modules.js?rev=136#L1433

Microsoft.XMLHTTP will always get versions up to 3. Checking for Msxml2.XMLHTTP is a waste of time since it always gets version 3. Msxml2.XMLHTTP.4.0 and 6.0 are not returned by Microsoft.XMLHTTP. 6.0 was released with Vista.

http://www.telerik.com/documents/AJAX%20Page/Ajax-Part1.pdf page 3

This is a great exercise for the Lazy Function Declaration pattern, if only for its educational value, or because try/catch is expensive.

This sample is pretty green though (in the arboreal sense). It doesn’t take into account status eccentricities of various browsers over various protocols. For example KHTML doesn’t mask the 304 cache hit status (other browsers handle it and change it to a 200). Also in some browsers, under various conditions, you’ll get “undefined” or “0″ for OK.

Comment by Kris Kowal — October 3, 2007

[quote] I don’t understand why frameworks must use a try/catch (try/catchs are usually not very fast, and very annoying with Firebug).[/quote]

Disable ActiveX and see what happens.

Comment by Eric Pascarello — October 3, 2007

@Eric

Considering your argument about disabling ActiveX, I’d still narrow the try/catch block down to the ActiveX control construction.

But you simply don’t need to try/catch anything, if ActiveX is disabled and window.XMLHttpRequest doesn’t exist you can perfectly verify that you got what you need without “trying”.

Comment by Rogier — October 3, 2007

@Rogier
Totally agree with you. Object detection is always the way to go.

My comment is basically why you probably would want to use the around the ActiveX. Talked about the error a long time ago on my blog here: http://radio.javaranch.com/pascarello/2006/02/07/1139345471027.html

Eric

Comment by Eric Pascarello — October 3, 2007

Am I the only one, who prefers higher level “complexity”? I know that try-catch is slow or that foreach-like syntax is bad for performance, but I prefer to let these things handled by frameworks (either inhouse, or for pet projects prototype.js) – hardware components and browsers are getting faster/better by the day (by the year, sry:)), but code reusability and readibility will not improve by itself.

Comment by deadcabbit — October 4, 2007

@deadcabbit What you say is true, but only if the effect is (near) transparent. In the case of try-catch it isn’t on the iPhone. It literally takes seconds to pass try catch blocks.

Comment by Anonymous — October 4, 2007

As others have already pointed out in the article comments, this code doesn’t work at all, because readyState is only checked once before sending the request (instead of polling or putting it on onreadystatechange event)

Comment by Mourner — October 4, 2007

Leave a comment

You must be logged in to post a comment.