在webkit中如何避免触发layout(重排)

很多web开发者都已经意识到,在脚本执行中,DOM操作的用时可能比js本身执行时间要长很多,其中潜在的消耗基本上是由于触发了layout(即重排reflow:由DOM树构建为Render渲染树的过程),DOM结构越大越复杂,则操作的代价越昂贵。

目前一个保持页面敏捷快速的比较重要的技巧就是将对dom的不同操作合并在一起,然后批量一次性改变dom的结构状态,比如:

// 不推荐的方式,会引起两次重排(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这篇文章已对此作出了非常精彩的解释。

由此,经常会有人问:到底什么会触发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工具中去分析瓶颈。

 

转载于:https://www.cnblogs.com/ppoo24/p/6626960.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值