原先写的ajax是这样的!!
function createXHR(){
var xhr;
try{
xhr=new XMLHttpRequest();
}catch(e){
try{
xhr=new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
alert(e);
}
}
}
return xhr;
}
这个有需要优化吗??
当然有!!!!想想,如果一个页面需要请求多个ajax对象,根据这个函数,我们需要对每次申请做if判断。但是!其实,我们只需要做一次if判断,之后怎样的结果和第一次if的结果那是一样一样的!!!这样,性能问题,就肯定会造成。
那该怎么办呢!!!
惰性载入函数!!!哈哈 就是这个东西啦~~,具体如下哦:
function createXHR(){
try{
createXHR=function(){
return new XMLHttpRequest();
}
}catch(e){
try{
createXHR=function(){
return new ActiveXObject("Microsoft.XMLHTTP");
}
}catch(e){
try{
creatXHR=function(){
return new ActiveXObject("Msxml2.XMLHTTP");
}
}catch(e){
return ;
}
}
}
return createXHR();
}
这个惰性载入,第一次做if判断,有效的 覆盖了原有的函数。所以下次不需要再次执行if语句了。
还有一种惰性载入,但是性能没有第一个好,但是也比原来的要好:
var createXHR=(function(){
try{
return function(){
return new XMLHttpRequest();
}
}catch(e){
try{
try{
return function(){
return new ActiveXObject("Msxml2.XMLHTTP");
}
}catch(e){
return function(){
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
}catch(e){
return ;
}
}
})();
这个例子创建了一个自执行的匿名函数,用来确定这个函数变量到底是指定的那个函数地址,从此以后这个createXHR变量指向的就是那个函数地址。 但是这个函数对与一个不需要xhr的页面来说牺牲了一点性能。