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.

Tags




blog comments powered by Disqus
search blog
random posts
  • Adobe-AIR-1-5-Cookbook-Application
  • Beginning-iPhone-Web-Apps-JavaScript
categories & tags
about hb stone

I'm a Front-End Engineer at Yahoo! working on the Mail and Messenger teams. I blog about web design and development topics including accessibility, usability, performance, and developing HTML / CSS / JavaScript applications on Appcelerator Titanium and Adobe AIR.

If you're a web developer, you might enjoy Jelo, my JavaScript library.

@hbstone follows:
@hbstone tweets:
  • Principles-Beautiful-Web-Design
  • Learning-MySQL-JavaScript-Step-Step
copyright

All original work on this site is covered by a Creative Commons Attribution 3.0 license unless otherwise specified.

You may share or use any code or images from this site in any manner, for free, so long as reasonable effort has been made to give credit where due.

The views expressed in the posts and comments on this blog do not necessarily reflect the views of Yahoo!