Skip to content

Instantly share code, notes, and snippets.

@CatTail
Created July 16, 2013 15:54
Show Gist options
  • Select an option

  • Save CatTail/6010006 to your computer and use it in GitHub Desktop.

Select an option

Save CatTail/6010006 to your computer and use it in GitHub Desktop.
Lazy loading function
/**
* <Professional Javascript for web developer v3 p736>
* Reduce determine condition in every function execution.
*/
// bad ass
function createXHR(){
if (typeof XMLHttpRequest != “undefined”){
return new XMLHttpRequest();
} else if (typeof ActiveXObject != “undefined”) {
if (typeof arguments.callee.activeXString != “string”){
var versions = [“MSXML2.XMLHttp.6.0”, “MSXML2.XMLHttp.3.0”,
“MSXML2.XMLHttp”],
i, len;
for (i=0,len=versions.length; i < len; i++){
try {
new ActiveXObject(versions[i]);
arguments.callee.activeXString = versions[i];
break;
} catch (ex){
//skip
}
}
}
return new ActiveXObject(arguments.callee.activeXString);
} else {
throw new Error(”No XHR object available.”);
}
}
// lazy loading
function createXHR(){
if (typeof XMLHttpRequest != “undefined”){
createXHR = function(){
return new XMLHttpRequest();
};
} else if (typeof ActiveXObject != “undefined”){
createXHR = function(){
if (typeof arguments.callee.activeXString != “string”){
var versions = [“MSXML2.XMLHttp.6.0”, “MSXML2.XMLHttp.3.0”,
“MSXML2.XMLHttp”],
i, len;
for (i=0,len=versions.length; i < len; i++){
try {
new ActiveXObject(versions[i]);
arguments.callee.activeXString = versions[i];
break;
} catch (ex){
//skip
}
}
}
return new ActiveXObject(arguments.callee.activeXString);
};
} else {
createXHR = function(){
throw new Error(“No XHR object available.”);
};
}
return createXHR();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment