JS操作效能最佳化

來源:互聯網
上載者:User

標籤:style   blog   color   使用   for   ar   div   log   

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 something5 }

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 數組的長度, 效率低。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.