zoukankan      html  css  js  c++  java
  • 在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工具中去分析瓶颈。

     
  • 相关阅读:
    获取定位
    关于meta 总结
    关于微信 ios的部分兼容(摇动播放)
    mysql
    js_DOM的导航属性--Dom_event事件
    IO阻塞与IO非阻塞2
    进程池
    生产消费者模型
    队列----------------多线程利器
    信号量
  • 原文地址:https://www.cnblogs.com/ppoo24/p/6626960.html
Copyright © 2011-2022 走看看