1. 适当使用变量
Maybe
1 document.getElementById("myField").style.backgroundColor = "#CCC"; 2 document.getElementById("myField").style.color = "#FF0000"; 3 document.getElementById("myField").style.fontWeight = "bold";
Better
1 var myField = document.getElementById("myField"); 2 3 myField.style.backgroundColor = "#CCC"; 4 myField.style.color = "#FF0000"; 5 myField.style.fontWeight = "bold";
每次调用document.getElementById("myField"),浏览器都要在 DOM 中搜索 ID 为 myField 的元素,效率低。
2. 元素尽量一次性应用全部样式
Maybe
1 var myField = document.getElementById("myField"); 2 myField.style.backgroundColor = "#CCC"; 3 myField.style.color = "#FF0000"; 4 myField.style.fontWeight = "bold";
Better
1 var myField = document.getElementById("myField"); 2 3 myField.style.cssText = "background-color: #CCC; color: #FF0000; font-weight: bold";
对 ID 为 myField 的元素,分别使用 style 应用三个不同的样式属性。将导致三次回流(reflow)和重绘(repaint),效率低,可以一次性应用全部样式,只导致一次回流和重绘。
3. for循环遍历数组
Maybe
1 var myArray = [1, 2, 3]; 2 3 for(var i=0; i < myArray.length; i++) { 4 //do something 5 }
Better
1 var i = 0, 2 myArray = [1, 2, 3], 3 len = myArray.lenght; 4 5 for(; i<len; i++){ 6 //do something 7 }
每次循环迭代时,i<myArray.length 都要重新计算 myArray.length 数组的长度, 效率低。
JS操作性能优化
时间: 2024-10-06 09:04:36