Ajax on IE 7: Check native first
I would hasten a guess that there is a lot of code out there that starts off with:
/*@cc_on
@if (@_jscript_version>= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
@else
xmlhttp = false;
@end @*/
if (!xmlhttp && typeof XMLHttpRequest != "undefined") {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
@if (@_jscript_version>= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
@else
xmlhttp = false;
@end @*/
if (!xmlhttp && typeof XMLHttpRequest != "undefined") {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
and what is wrong with this? Well, apart from being pretty verbose, in the world of IE7 we should be invoking XMLHttpRequest() first and having the ActiveX control done only if window.XMLHttpRequest isn't around to play.
Source: Ajaxian
Original Article: http://ajaxian.com/archives/ajax-on-ie-7-check-native-first
on June 9th, 2006 at 12:36 am
[…] An XMLHTTPRequest tip Over on the Ajax Blog, Dion Almaer passed on an important tip from Brent Ashley and Tim Aiello for AJAX developers – to have your cross-browser AJAX work better with IE7, you really should be invoking the native XMLHTTPRequest (the cross-browser one) first to see if it’s available before instantiating the ActiveX control, instead of the other way around. In addition to the reasons that Brent and Tim discovered, I’ve seen a bunch of code that creates the XMLHTTPRequest object, uses it for a request, and then throws it away. Obviously, this is a lot less performant than keeping the object around for multiple requests. The native object’s lifetime can be as long as that of the page. So you can reuse it like this: var o = new XMLHttpRequestObject() o.open(“GET”, “data1.xml”, TRUE); o.onreadystatechange = foo(); o.send(); ……. o.open(“GET”, “data2.xml”, TRUE); o.onreadystatechange=bar(); o.send(); Xmlhttp.open has a “reset” semantic so the second open() call on the same object will abort the previous connection, disconnect previous event handler, and reset the object. There’s also a handy tool by Julien Couvreur for debugging XHTMLHTTPRequest calls for IE, or you can use Fiddler. -Chris Published Thursday, June 08, 2006 3:30 PM by ieblog Filed Under: Tips and Tricks, Developers […]