Properly create the XMLHttpRequest object

Posting this as a reminder for the future. IE 7 will support the native XMLHttpRequest object, but the older versions will continue to use the ActiveX object. Right now, when creating the XMLHttpRequest object, the norm is to attempt to instantiate the ActiveX object, if that does not work, then attempt to use the native implementation. I saw a better recommendation on Joe Walker’s blog.

This will attempt to create a native object first, which will work for IE7 and other browsers, and only attempt to create the ActiveX object as a last resort.


var xhr;
if (window.XMLHttpRequest) {
  xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
  xhr = new ActiveXObject("Msxml2.XMLHTTP");
}

One Comment for “Properly create the XMLHttpRequest object”

  1. A more complete code example

    var xhr;
    if (window.XMLHttpRequest) {
      try {
        xhr = new XMLHttpRequest();
      } catch (e) {
        xhr = false;
      }
    } else if (window.ActiveXObject) {
      try {
        xhr = new ActiveXObject(“Msxml2.XMLHTTP”);
      } catch( e ) {
        try {
          xhr = new ActiveXObject(“Microsoft.XMLHTTP”);
        } catch( e ) {
          xhr = false;
        }
      }
    }


Comments are closed.