start blog post

AJAX: Cross-Browser XMLHttpRequest

The term AJAX has grown to encompass a broad range of technologies and programming methodologies. As you'll find throughout web development, there's often a DOM way to do something, and then there's The Microsoft Way to do it. In this case, there are actually two Microsoft ways.

    var http = function() {
        try {
            return new XMLHttpRequest();
        } catch (e) {}
        try {
            return new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {}
        try {
            return new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {}
        return null;
    }(); // inline execution

You can think of this pattern as the Good, the Bad, and the Ugly.

  • The Good: The first try/catch block uses the DOM API standard method of generating an XMLHttpRequest object. Most browsers implement this method, including Firefox, Safari, Opera, Google Chrome, and a host of others.
  • The Bad: Msxml2.XMLHTTP is IE's AJAX object. Msxml2.XMLHTTP is actually the preferred of the two IE objects, according to the Microsoft XML Team.
  • The Ugly: Microsoft.XMLHTTP is bound to version 2.0 of Microsoft's implementation of the XMLHttpRequest object, while Msxml2.XMLHTTP (despite the name...) has progressed to at least version 6.0, possibly beyond. But if you're wondering why your killer app doesn't work in IE5 on Windows 98, make sure you include that third try/catch block!

The beauty of this above pattern is that you don't have to try to detect what browser your visitor is running, nor do object detection to determine which code to execute.

Semantically, I should mention that object detection is probably the "right" way to create this object. If you're going to use try/catch blocks, you should actually handle the error, not have empty catches. However, in this particular case I believe this pattern to be the most efficient and easiest to understand way to create your AJAX object.

var tags = [, ];

  • share this post:
  • email a friend
  • float this post
  • digg this post
  • share on stumbleupon
  • submit to technorati
  • tweet this post

end blog post

most viewed this week

least viewed this week