What is DOM?
- applications for manipulating XML and HTML documents
- DOM Node 2. Dom Tree 3.Dom API
Dom optimization
- The browser will be JS and Dom independent implementation, JS each operation of the DOM, will add a time-consuming, in order to improve the performance of the DOM, it is necessary to minimize the operation of JS Dom,
Here are two Tests
1<script>2Window.onload=function(){3 varDiv=document.getelementbyid (' div ');4 varStr= ";5Console.time (' test1 ');6 for(vari=0;i<5000;i++){7div.innerhtml+= ' a ';8 }9Console.timeend (' test1 ');//Firefox under test time 152msTen OneConsole.time (' Test2 '); A for(i=0;i<5000;i++){ -str+= ' a '; - } theDiv.innerhtml=str; -Console.timeend (' test2 ');//Firefox under test time 1.36ms - }; -</script> + -<body> +<div id= "Div" ></div> A</body>
As you can see, TEST2 only operates one DOM at a time, which improves performance.
- Ways to reduce DOM operations:
- Use node clone Node.clonenode () instead of creating a new repeating node
- Use local variables instead of access node collections, such as
var doc=document; var div=doc.getelementbyid (' div '); var input=doc.getelementbyid (' input ');
- Try to get only the element nodes, for example using children instead of childnodes firstelementchild instead of FirstChild
- Selector API: Use Queryselectorall (except for browsers with IE8 below are well supported)
Dom and browser
- Reflow: The process of changing the content of a page
- Redraw: The process by which the browser displays content after the rearrangement is finished
The process of reflow and redraw can be reduced in the following ways to improve browser performance
- Try to work in front of AppendChild ()
1 for(vari=0;i<50000;i++){2 varLi=document.createelement (' Li ');3 //Not recommended4 Ul.appendchild (LI);5Li.innerhtml= ' Li ';6 } 7 for(i=0;i<5000;i++){8 varLi=document.createelement (' Li ');9 //RecommendedTenLi.innerhtml= ' Li '; One Ul.appendchild (LI); A}
- Using Csstext to merge DOM operations
- Caches layout information. For example:
1Window.onload =function(){2 varOdiv = document.getElementById (' Div1 '));3 varL =Odiv.offsetleft;4 varT =Odiv.offsettop;5SetInterval (function(){6l++;7t++;8ODiv.style.left = L + ' px ';9ODiv.style.top = T + ' px ';Ten},30); One};
- Take advantage of document fragmentation
1Window.onload =function(){2 varOul = document.getElementById (' ul1 '));3 varOfrag =document.createdocumentfragment ();4 for(vari=0;i<5000;i++){5 varOLi = document.createelement (' li ');6 Ofrag.appendchild (oLi);7 }8 Oul.appendchild (Ofrag);9};
Dom and Events
Dom and front-end templates
- Better separation of logic and views, the basis of the MVC framework
JS Performance DOM Optimization