Legacy code to create XMLHttpRequest still valid?
javascript, xmlhttprequest
Solution
I remember using this code, some four, five years ago? When the technique first got developed and was still being argued about (anyone remember the don't disable the back button argument?), it was still somewhat patchily supported; this would be around Firefox 1/2. If I recall, this originated as an MS Outlook library that was used to make the Outlook client more responsive, and eventually the technique bled over into browsers.
Having said that, the last two lines are legacy; all modern browsers have and do support the plain `XMLHttpRequest`, and the last two were only meant for IE anyhow. In the future, this will perhaps be shortened to `HTTP` or `AsyncRequest` or whatever, but the fact is, unless you need to support IE6, you really only need the first line.
To wit:
To support versions of Windows Internet Explorer prior to Internet Explorer 7, use the following function to get the XMLHttpRequest object.
function getXMLHttpRequest() {
if (window.XMLHttpRequest) {
return new window.XMLHttpRequest;
}
else {
try {
return new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
catch(ex) {
return null;
}
}
}
http://msdn.microsoft.com/en-us/library/ie/ms535874%28v=vs.85%29.aspx
So, you don't really need it anymore. As Truth says, libraries like jQuery, Angular and their ilk will subsume this into the background over time. But accessing it directly is not a problem either.
Also worth linking to MSDN's About Native XMLHTTP, courtesy of RobW's comment under the question. The gist of this is that Group Policy or individual IE policy may disable native `XMLHttpRequest`, so it may still be useful to enable `ActiveX` as a workaround, although (at least at this point) it seems a little crayon tinfoil to disable that while allowing the much more "problematic" `ActiveX` subsystem. A possible explanation of this is bandwidth, concurrent connections or some other network-level concern. Weird.
Problem
For years I am using the same code snippet to create the `XMLHttpRequest` object: ``` var tReq = (function () { var tAn; if (window.XMLHttpRequest) { tAn = new XMLHttpRequest(); } else if (window.ActiveXObject) try { tAn = new ActiveXObject("MSXML2.XMLHTTP"); } catch (ex) { tAn = new ActiveXObject("Microsoft.XMLHTTP"); } return tAn; }()); ``` I have been using that code for so long that I do not know if it is still up to date. Does this code still create the `XMLHttpRequest` in every browser or is there a more efficient solution nowadays (not asking for jQuery)?