In JS, some memory only needs to be executed once, such as browser type detection is the most commonly used function, because when we use Ajax, we need to detect the browser's built-in XHR. We can record the type during the first detection, and in the future, we no longer need to detect the browser type when using Ajax. Even if there is only one if in JS, it is always more efficient than statements without an if.
Normal Ajax method
The code copy is as follows:
/**
* JS lazy function
*/
function ajax(){
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"];
for(var i=0,k=version.length;i<k;i++){
try{
new ActiveXObject(versions[i]);
arguments.callee.activeXString = versions[i];
break;
}catch(ex){
throw ex;
}
}
}
return new ActiveXObject(arguments.callee.activeXString);
}else{
throw "No XHR object";
}
}
Every time ajax() function is called, the browser's built-in XHR check is not efficient.
How to use lazy methods
The code copy is as follows:
/**
* JS lazy function
*/
function ajax(){
if(typeof XMLHttpRequest != "undefined"){
ajax = function(){
return new XMLHttpRequest();
};
}else if(typeof ActiveXObject != "undefined"){
ajax = function(){
if(typeof arguments.callee.activeXString != "string"){
var versions = ["MSXML2.XMLHttp.6.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp"];
for(var i=0,k=version.length;i<k;i++){
try{
var xhr = new ActiveXObject(versions[i]);
arguments.callee.activeXString = versions[i];
return xhr;
}catch(ex){
throw ex;
}
}
}
return new ActiveXObject(arguments.callee.activeXString);
}
}else{
ajax = function(){
throw "No XHR object";
}
}
return ajax();
}
In the second lazy method, each branch of if will assign a value to the ajax() variable, effectively overwriting the original function, and the new function is called in the last step. The next time ajax() is called, the variable is called directly.
Optimization focus
To execute a specific code, only the actual call is executed, while some JS libraries detect the browser at the beginning and are pre-set.
Due to the complex judgment, the first run speed is slow, but the subsequent multi-book run will be faster.
Sometimes, after writing code for a long time, you cannot remain unchanged. You must often think about how to make the program run faster and more efficient. The program written under such thoughts is hardcover and will not produce unnecessary junk code. This is not a simple OO-size-fits-all approach. In fact, many parts of the code live, and people live even more.