在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

相关文章
相关标签/搜索