Javascript to retrieve all images of the document
Function updateUI (){
Var imgs = document. getElementsByTagName ("img ");
For (var I = 0, len = imgs. length; I <len; I ++ ){
Imgs [I]. title = document. title + "image" + I;
}
Var msg = document. getElementById ("msg ");
Msg. innerHTML = "Update complete .";
}
This function may seem completely normal, but it has three reference global document objects. If there is a page
The number of images is large, and dozens or hundreds of times can be executed in the circular reference file.
Chain. By creating a Document Object point for a local variable, you can add a limit that some global searches only have one
Function performance:
Function updateUI (){
Var doc = document;
Var imgs = doc. getElementsByTagName ("img ");
For (var I = 0, len = imgs. length; I <len; I ++ ){
Imgs [I]. title = doc. title + "image" + I;
}
Here, the first document object is stored in the local document variable. This document variable is then stored in the entire
The rest of the code. Only one global function is found here, which is faster than the previous version.
. A good rule of thumb is that any global storage object is used as a local variable more than once in a function.
.
Avoidance and Declaration
With statements should be avoided in performance. Similar function, it has the ability to create its own range for statements, so it is added
The length of the range chain in the executed code. The statement of the executed Code ensures that the code runs faster than the execution speed,
This is because of the additional steps for searching for a range chain. This is a rare statement that is required because it is mainly used to eliminate multiple
Remaining characters. In most cases, local variables can be used to accomplish the same thing without introducing a new range.
. The following is an example:
Function updateBody (){
With (document. body ){
Alert (tagName );
InnerHTML = "Hello world! ";
}
}
Function updateBody (){
Var body = document. body
Alert (body. tagName );
Body. innerHTML = "Hello world! ";
}
This Code uses document. body to make it easier to speak. The same effect can be achieved by using a local variable.
, As follows:
Var msg = doc. getElementById ("msg ");
Msg. innerHTML = "Update complete .";
}