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工具中去分析瓶颈。

     
  • 相关阅读:
    SQLSERVER查询某张表哪些字段包含某关键字
    SQLSERVER初始化机构path
    Golang的ORM框架之gorm
    Golang的web框架之Gin
    初识Go逆向
    GIT 常用命令
    mac上系统偏好里无法停止mysql
    js正则高级用法: 分组和断言
    Java强软弱虚四种引用的使用场景
    两数之和
  • 原文地址:https://www.cnblogs.com/ppoo24/p/6626960.html
Copyright © 2011-2022 走看看