在webkit中如何避免觸發layout(重排)

不少web開發者都已經意識到,在腳本執行中,DOM操做的用時可能比js自己執行時間要長不少,其中潛在的消耗基本上是因爲觸發了layout(即重排reflow:由DOM樹構建爲Render渲染樹的過程),DOM結構越大越複雜,則操做的代價越昂貴。php

目前一個保持頁面敏捷快速的比較重要的技巧就是將對dom的不一樣操做合併在一塊兒,而後批量一次性改變dom的結構狀態,好比:web

// 不推薦的方式,會引發兩次重排(layout)
var newWidth = aDiv.offsetWidth + 10; // 讀取
aDiv.style.width = newWidth + 'px'; // 更新樣式
var newHeight = aDiv.offsetHeight + 10; // 讀取
aDiv.style.height = newHeight + 'px'; // 更新樣式

// 推薦,僅觸發1次重排
var newWidth = aDiv.offsetWidth + 10; // 讀取
var newHeight = aDiv.offsetHeight + 10; // 讀取
aDiv.style.width = newWidth + 'px'; // 更新
aDiv.style.height = newHeight + 'px'; // 更新

Stoyan Stefanovtome on repaint, relayout and restyle這篇文章已對此做出了很是精彩的解釋。dom

由此,常常會有人問:到底什麼會觸發layout?Dimitri Glazkov 在此回答了這個問題。便於我本身理解,我將這些會致使layout的DOM的屬性和方法弄成了一個列表,以下:工具

Element

clientHeight, clientLeft, clientTop, clientWidth, focus(), getBoundingClientRect(), getClientRects(), innerText, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerText, scrollByLines(), scrollByPages(), scrollHeight, scrollIntoView(), scrollIntoViewIfNeeded(), scrollLeft, scrollTop, scrollWidth

Frame, Image

height, width

Range

getBoundingClientRect(), getClientRects()

SVGLocatable

computeCTM(), getBBox()

SVGTextContent

getCharNumAtPosition(), getComputedTextLength(), getEndPositionOfChar(), getExtentOfChar(), getNumberOfChars(), getRotationOfChar(), getStartPositionOfChar(), getSubStringLength(), selectSubString()

SVGUse

instanceRoot

window對象

getComputedStyle(), scrollBy(), scrollTo(), scrollX, scrollY, webkitConvertPointFromNodeToPage(), webkitConvertPointFromPageToNode()

列表並不完善,但算是一個開始吧,其實最好的方式,固然是在Timeline工具中去分析瓶頸。post

相關文章
相關標籤/搜索