Optimization issues related to javascript programs
These are some of my experiences when writing code. I summarized them for everyone. There is no order. I wrote them as soon as I thought of them.
1. Use local variables to avoid using global variables. For example,
function test(){
var s = document.getElementById('aaa');
s.innerHTML = document.body.clientHeight;
s = d.getElementById('aaa');
s.innerHTML = d.body.clientHeight;
}
The advantage of local variables is that it reduces the scope chain search
I suggest using local variables if there are two references
2. Avoid using with (this estimate of the earth Everyone knows)
I understand the reason is that with will create its own scope, which lengthens the original scope chain, making the code executed in the with block slower. It seems to save code in writing, but in fact On the contrary, the access becomes longer and more cumbersome, and the performance decreases. ClientHeight = '200px';
It can be written as
function test(){ var ds = document.body; ds.clientWidth = '200px'
var as = document.getElementsByTagName('div');
for(var i=0,l
for( var i=0,ci;ci=as[i++];){}When nodeList is completed, it will be false and it will end
Advantages: No length calculation, no assignment in the loop, less code, i++ is included in the judgment
(注意:这个方式用在nodelist里可以,如果你用到array里,可会有问题的,数组里有个0后者null什么的就瞎了)
4.别用那么多个var, Just add a comma and you’re done
var a =1;
var b = 1;
var c =1;
b=1,
c=1;
5.innerHTML is the best choice
When adding elements to elements, it is best to use innerHTML
6.ie's removeChild is not easy to use
Generally when we delete an element, we will use elm.removeChild(subElm)
This is in ie It’s not easy to use, because under IE this only disconnects the element from the DOM tree, but does not actually delete it. It has now become an isolated node.
If you want to really delete it, you can do this
var ryc = document.createElement('div');
div.appendChild(subElm);
div.innerHTML = '';
div = null;
This way it is really deleted. Except for IE, you can use removeChild to achieve the effect
7. When binding events to multiple sibling elements, there is no need to bind events for each element. Bind them all, just bind them to their parent
For example
;/li>