Some of the memory in JS can only be performed once, such as browser type detection is the most commonly used as a function, because we use AJAX when we need to detect the browser's built-in XHR. We can record the type on the first test, and we don't need to detect the browser type again when we use Ajax. Even a single if in JS is more efficient than a statement without if.
Common Ajax Methods
Copy Code code 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 the Ajax () function is invoked, the browser's built-in XHR check is not efficient.
Ways to use lazy methods
Copy Code code 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 ();
}
Each branch of if in the second lazy method assigns a value to the Ajax () variable, effectively overwriting the original function, and the last step calls the new function. The next time Ajax () is invoked, the variable is called directly.
Optimization Focus
To execute a specific code only the actual call is executed, and some JS libraries start by detecting the browser and setting it up beforehand.
The first run is slow because of complex judgments, but the number of volumes behind it runs faster.
Sometimes write code for a long time, can not be static, to often think how to make the program run faster, more efficient. This kind of thinking under the written program is hardcover, and will not produce redundant garbage code. This is not simple oo can across, in fact, many parts of the code is alive, people are more alive.