首页 > 代码库 > DOM优化

DOM优化

不要频繁操作DOM

 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4     <meta charset="UTF-8"> 5     <title>Document</title> 6 </head> 7 <body> 8     <div id="div1"></div> 9     <script>10     //不要频繁操作DOM11     var oDiv = document.getElementById("div1");12     var str = "";13     console.time("time1");14     for(var i = 0;i < 5000;i ++){15         oDiv.innerHTML += "a";16     }17     console.timeEnd("time1");18 19     console.time("time2");20     for(var i = 0;i < 5000;i ++){21         str += "a";22     }23     oDiv.innerHeight = str;24     console.timeEnd("time2");25     </script>26 </body>27 </html>

innerHTML和appendChild

 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4     <meta charset="UTF-8"> 5     <title>Document</title> 6 </head> 7 <body> 8     <ul id="ul1"></ul> 9     <script>10     //chrome中DOM比innerHTML性能高,不同浏览器写会有差异11     var oUl = document.getElementById("ul1");12     var str = "";13 14     console.time("time1");15     for(var i = 0;i < 50000;i ++){16         var oLi = document.createElement("li");17         oUl.appendChild(oLi);18     }19     console.timeEnd("time1");20 21     console.time("time2");22     for(var i = 0;i < 50000;i ++){23         str += "<li></li>";24     }25     oUl.innerHTML = str;26     console.timeEnd("time2");27     </script>28 </body>29 </html>

先创建一个再cloneNode比每次都createElement性能要好一点

...

1 var len = aLi.length;2 for(var i = 0;i < len;i ++){ ... }
1 childNodes  元素节点和文本节点  >>  children元素节点2 firstChild  >>  firstElementChild   

querySelector

1 querySelector("#ul1 li")//第一个li2 querySelectorAll("#ul1 li");//所有li

//重排:改变DOM结构
//重绘:浏览器显示变化

添加内容在appendChild之前

合并DOM操作:cssText

缓存布局信息

1 var L = oDiv.offsetLeft;2 var T = oDiv.offsetTop;3 4 setInterval(function(){5     L ++;6     T ++;7     oDiv.style.left = L + "px";8     oDiv.style.top = T + "px";9 },30);

文档碎片:document.createDocumentFragment()

前端模板:基于jQuery的tmpl

DOM优化