This article mainly introduces JavaScriptAJAX's inert loading function. It indicates that the branch of function execution only happens once. It is a JS optimization technique, for more information, see some memory in JS. For example, browser type detection is the most commonly used function, because we need to check the built-in XHR of the browser when using Ajax. We can record the type during the first detection, and do not need to check the browser type when using Ajax later. In JS, even if there is only one if statement, it is always more efficient than the statement without if.
Common Ajax Method
The Code is as follows:
/**
* JS inertia Functions
*/
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 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 you call an ajax () function, you must check the browser's built-in XHR, Which is inefficient.
Method of Using inertia
The Code is as follows:
/**
* JS inertia Functions
*/
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 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 method, each branch of the if will assign a value to the ajax () variable, effectively overwriting the original function, and calling the new function in the last step. When ajax () is called next time, the variable is called directly.
Optimization focus
To execute specific code, only actual calls are required. Some JS libraries detect the browser at the beginning and are pre-configured.
Because of the complicated judgment, the first operation speed is slow, but the efficiency of multiple subsequent operations will be faster.
Sometimes the code has been written for a long time and cannot be changed. You must always think about how to make the program run faster and more efficient. The program written in this way is hard‑packed without generating additional junk code. This is not a simple way to achieve a one-size-fits-all. In fact, code is active in many places, and people are even more active.