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.
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.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.
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.
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!