加入收藏 | 设为首页 | 会员中心 | 我要投稿 焦作站长网 (https://www.0391zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 服务器 > 安全 > 正文

高性能WEB开发 页面呈现、重绘、回流。

发布时间:2020-03-16 09:46:22 所属栏目:安全 来源:互联网
导读:在讨论页面重绘、回流之前。需要对页面的呈现流程有些了解,页面是怎么把html结合css等显示到浏览器上的,下面的流程图显示了浏览器对页面的呈现的处理流程。可

// 别这样写,大哥
for(循环) {
    el.style.left = el.offsetLeft + 5 + "px";
    el.style.top  = el.offsetTop  + 5 + "px";
}

// 这样写好点
var left = el.offsetLeft,top  = el.offsetTop,s = el.style;
for(循环) {
    left += 10;
    top  += 10;
    s.left = left + "px";
    s.top  = top  + "px";
}


    4. 考虑你的操作会影响到render tree中的多少节点以及影响的方式,影响越多,花费肯定就越多。比如现在很多人使用jquery的animate方法移动元素来展示一些动画效果,想想下面2种移动的方法:

// block1是position:absolute 定位的元素,它移动会影响到它父元素下的所有子元素。

// 因为在它移动过程中,所有子元素需要判断block1的z-index是否在自己的上面,
// 如果是在自己的上面,则需要重绘,这里不会引起回流
$("#block1").animate({left:50});

// block2是相对定位的元素,这个影响的元素与block1一样,但是因为block2非绝对定位
// 而且改变的是marginLeft属性,所以这里每次改变不但会影响重绘,
// 还会引起父元素及其下元素的回流

$("#block2").animate({marginLeft:50});


实例测试

    最后用2个工具对上面的理论进行一些测试,这2个工具是在我 "web 性能测试工具推荐" 文章中推荐过的工具,分别是:dynaTrace(测试ie),Speed Tracer(测试Chrome)。

    第一个测试代码不改变元素的规则,大小,位置。只改变颜色,所以不存在回流,仅测试重绘,代码如下:

<body>
    <script type="text/javascript">
        var s = document.body.style;
        
var computed;
        
if (document.body.currentStyle) {
          computed 
= document.body.currentStyle;
        } 
else {
          computed 
= document.defaultView.getComputedStyle(document.body, '');
        }
    
function testOneByOne(){
      s.color 
= 'red';;
      tmp 
= computed.backgroundColor;
      s.color 
= 'white';
      tmp 
= computed.backgroundImage;
      s.color 
= 'green';
      tmp 
= computed.backgroundAttachment;
    }

    
function testAll() {
      s.color 
= 'yellow';
      s.color 
= 'pink';
      s.color 
= 'blue';

      tmp 
= computed.backgroundColor;
      tmp 
= computed.backgroundImage;
      tmp 
= computed.backgroundAttachment;
    }
    
</script>    
    color test <br />
    <button onclick="testOneByOne()">Test One by One</button>
    <button onclick="testAll()">Test All</button>
</body>        

    testOneByOne 函数改变3次color,其中每次改变后调用getComputedStyle,读取属性值(按我们上面的讨论,这里会引起队列的flush),testAll 同样是改变3次color,但是每次改变后并不马上调用getComputedStyle
我们先点击Test One by One按钮,然后点击 Test All,用dynaTrace监控如下:

(编辑:焦作站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读