网页性能管理详解

转自作者: 阮一峰

http://www.ruanyifeng.com/blog/2015/09/web-page-performance-in-depth.html

你遇到过性能很差的网页吗?

这种网页响应非常缓慢,占用大量的CPU和内存,浏览起来常常有卡顿,页面的动画效果也不流畅。

你会有什么反应?我猜想,大多数用户会关闭这个页面,改为访问其他网站。作为一个开发者,肯定不愿意看到这种情况,那么怎样才能提高性能呢?

本文将详细介绍性能问题的出现原因,以及解决方法。

一、网页生成的过程

要理解网页性能为什么不好,就要了解网页是怎么生成的。

网页的生成过程,大致可以分成五步。

  1. HTML代码转化成DOM
  2. CSS代码转化成CSSOM(CSS Object Model)
  3. 结合DOM和CSSOM,生成一棵渲染树(包含每个节点的视觉信息)
  4. 生成布局(layout),即将所有渲染树的所有节点进行平面合成
  5. 将布局绘制(paint)在屏幕上

这五步里面,第一步到第三步都非常快,耗时的是第四步和第五步。

“生成布局”(flow)和”绘制”(paint)这两步,合称为”渲染”(render)。

二、重排和重绘

网页生成的时候,至少会渲染一次。用户访问的过程中,还会不断重新渲染。

以下三种情况,会导致网页重新渲染。

  • 修改DOM
  • 修改样式表
  • 用户事件(比如鼠标悬停、页面滚动、输入框键入文字、改变窗口大小等等)

重新渲染,就需要重新生成布局和重新绘制。前者叫做”重排”(reflow),后者叫做”重绘”(repaint)。

需要注意的是,”重绘”不一定需要”重排”,比如改变某个网页元素的颜色,就只会触发”重绘”,不会触发”重排”,因为布局没有改变。但是,”重排”必然导致”重绘”,比如改变一个网页元素的位置,就会同时触发”重排”和”重绘”,因为布局改变了。

三、对于性能的影响

重排和重绘会不断触发,这是不可避免的。但是,它们非常耗费资源,是导致网页性能低下的根本原因。

提高网页性能,就是要降低”重排”和”重绘”的频率和成本,尽量少触发重新渲染。

前面提到,DOM变动和样式变动,都会触发重新渲染。但是,浏览器已经很智能了,会尽量把所有的变动集中在一起,排成一个队列,然后一次性执行,尽量避免多次重新渲染。

div.style.color = 'blue';
div.style.marginTop = '30px';

上面代码中,div元素有两个样式变动,但是浏览器只会触发一次重排和重绘。

如果写得不好,就会触发两次重排和重绘。

div.style.color = 'blue';
var margin = parseInt(div.style.marginTop);
div.style.marginTop = (margin + 10) + 'px';

上面代码对div元素设置背景色以后,第二行要求浏览器给出该元素的位置,所以浏览器不得不立即重排。

一般来说,样式的写操作之后,如果有下面这些属性的读操作,都会引发浏览器立即重新渲染。

  • offsetTop/offsetLeft/offsetWidth/offsetHeight
  • scrollTop/scrollLeft/scrollWidth/scrollHeight
  • clientTop/clientLeft/clientWidth/clientHeight
  • getComputedStyle()

所以,从性能角度考虑,尽量不要把读操作和写操作,放在一个语句里面。


// bad
div.style.left = div.offsetLeft + 10 + "px";
div.style.top = div.offsetTop + 10 + "px";

// good
var left = div.offsetLeft;
var top  = div.offsetTop;
div.style.left = left + 10 + "px";
div.style.top = top + 10 + "px";

一般的规则是:

  • 样式表越简单,重排和重绘就越快。
  • 重排和重绘的DOM元素层级越高,成本就越高。
  • table元素的重排和重绘成本,要高于div元素

四、提高性能的九个技巧

有一些技巧,可以降低浏览器重新渲染的频率和成本。

第一条是上一节说到的,DOM 的多个读操作(或多个写操作),应该放在一起。不要两个读操作之间,加入一个写操作。

第二条,如果某个样式是通过重排得到的,那么最好缓存结果。避免下一次用到的时候,浏览器又要重排。

第三条,不要一条条地改变样式,而要通过改变class,或者csstext属性,一次性地改变样式。


// bad
var left = 10;
var top = 10;
el.style.left = left + "px";
el.style.top  = top  + "px";

// good 
el.className += " theclassname";

// good
el.style.cssText += "; left: " + left + "px; top: " + top + "px;";

第四条,尽量使用离线DOM,而不是真实的网面DOM,来改变元素样式。比如,操作Document Fragment对象,完成后再把这个对象加入DOM。再比如,使用 cloneNode() 方法,在克隆的节点上进行操作,然后再用克隆的节点替换原始节点。

第五条,先将元素设为display: none(需要1次重排和重绘),然后对这个节点进行100次操作,最后再恢复显示(需要1次重排和重绘)。这样一来,你就用两次重新渲染,取代了可能高达100次的重新渲染。

第六条,position属性为absolute或fixed的元素,重排的开销会比较小,因为不用考虑它对其他元素的影响。

第七条,只在必要的时候,才将元素的display属性为可见,因为不可见的元素不影响重排和重绘。另外,visibility : hidden的元素只对重绘有影响,不影响重排。

第八条,使用虚拟DOM的脚本库,比如React等。

第九条,使用 window.requestAnimationFrame()、window.requestIdleCallback() 这两个方法调节重新渲染(详见后文)。

五、刷新率

很多时候,密集的重新渲染是无法避免的,比如scroll事件的回调函数和网页动画。

网页动画的每一帧(frame)都是一次重新渲染。每秒低于24帧的动画,人眼就能感受到停顿。一般的网页动画,需要达到每秒30帧到60帧的频率,才能比较流畅。如果能达到每秒70帧甚至80帧,就会极其流畅。

大多数显示器的刷新频率是60Hz,为了与系统一致,以及节省电力,浏览器会自动按照这个频率,刷新动画(如果可以做到的话)。

所以,如果网页动画能够做到每秒60帧,就会跟显示器同步刷新,达到最佳的视觉效果。这意味着,一秒之内进行60次重新渲染,每次重新渲染的时间不能超过16.66毫秒。

一秒之间能够完成多少次重新渲染,这个指标就被称为”刷新率”,英文为FPS(frame per second)。60次重新渲染,就是60FPS。

如果想达到60帧的刷新率,就意味着JavaScript线程每个任务的耗时,必须少于16毫秒。一个解决办法是使用Web Worker,主线程只用于UI渲染,然后跟UI渲染不相干的任务,都放在Worker线程。

六、开发者工具的Timeline面板

Chrome浏览器开发者工具的Timeline面板,是查看”刷新率”的最佳工具。这一节介绍如何使用这个工具。

首先,按下 F12 打开”开发者工具”,切换到Timeline面板。

左上角有一个灰色的圆点,这是录制按钮,按下它会变成红色。然后,在网页上进行一些操作,再按一次按钮完成录制。

Timeline面板提供两种查看方式:横条的是”事件模式”(Event Mode),显示重新渲染的各种事件所耗费的时间;竖条的是”帧模式”(Frame Mode),显示每一帧的时间耗费在哪里。

先看”事件模式”,你可以从中判断,性能问题发生在哪个环节,是JavaScript的执行,还是渲染?

不同的颜色表示不同的事件。

  • 蓝色:网络通信和HTML解析
  • 黄色:JavaScript执行
  • 紫色:样式计算和布局,即重排
  • 绿色:重绘

哪种色块比较多,就说明性能耗费在那里。色块越长,问题越大。

帧模式(Frames mode)用来查看单个帧的耗时情况。每帧的色柱高度越低越好,表示耗时少。

你可以看到,帧模式有两条水平的参考线。

下面的一条是60FPS,低于这条线,可以达到每秒60帧;上面的一条是30FPS,低于这条线,可以达到每秒30次渲染。如果色柱都超过30FPS,这个网页就有性能问题了。

此外,还可以查看某个区间的耗时情况。

或者点击每一帧,查看该帧的时间构成。

七、window.requestAnimationFrame()

有一些JavaScript方法可以调节重新渲染,大幅提高网页性能。

其中最重要的,就是 window.requestAnimationFrame() 方法。它可以将某些代码放到下一次重新渲染时执行。

function doubleHeight(element) {
  var currentHeight = element.clientHeight;
  element.style.height = (currentHeight * 2) + 'px';
}
elements.forEach(doubleHeight);

上面的代码使用循环操作,将每个元素的高度都增加一倍。可是,每次循环都是,读操作后面跟着一个写操作。这会在短时间内触发大量的重新渲染,显然对于网页性能很不利。

我们可以使用window.requestAnimationFrame(),让读操作和写操作分离,把所有的写操作放到下一次重新渲染。

function doubleHeight(element) {
  var currentHeight = element.clientHeight;
  window.requestAnimationFrame(function () {
    element.style.height = (currentHeight * 2) + 'px';
  });
}
elements.forEach(doubleHeight);

页面滚动事件(scroll)的监听函数,就很适合用 window.requestAnimationFrame() ,推迟到下一次重新渲染。

$(window).on('scroll', function() {
   window.requestAnimationFrame(scrollHandler);
});

当然,最适用的场合还是网页动画。下面是一个旋转动画的例子,元素每一帧旋转1度。

var rAF = window.requestAnimationFrame;

var degrees = 0;
function update() {
  div.style.transform = "rotate(" + degrees + "deg)";
  console.log('updated to degrees ' + degrees);
  degrees = degrees + 1;
  rAF(update);
}
rAF(update);

八、window.requestIdleCallback()

还有一个函数window.requestIdleCallback(),也可以用来调节重新渲染。

它指定只有当一帧的末尾有空闲时间,才会执行回调函数。

requestIdleCallback(fn);

上面代码中,只有当前帧的运行时间小于16.66ms时,函数fn才会执行。否则,就推迟到下一帧,如果下一帧也没有空闲时间,就推迟到下下一帧,以此类推。

它还可以接受第二个参数,表示指定的毫秒数。如果在指定 的这段时间之内,每一帧都没有空闲时间,那么函数fn将会强制执行。

requestIdleCallback(fn, 5000);

上面的代码表示,函数fn最迟会在5000毫秒之后执行。

函数 fn 可以接受一个 deadline 对象作为参数。

requestIdleCallback(function someHeavyComputation(deadline) {
  while(deadline.timeRemaining() > 0) {
    doWorkIfNeeded();
  }

  if(thereIsMoreWorkToDo) {
    requestIdleCallback(someHeavyComputation);
  }
});

上面代码中,回调函数 someHeavyComputation 的参数是一个 deadline 对象。

deadline对象有一个方法和一个属性:timeRemaining() 和 didTimeout。

(1)timeRemaining() 方法

timeRemaining() 方法返回当前帧还剩余的毫秒。这个方法只能读,不能写,而且会动态更新。因此可以不断检查这个属性,如果还有剩余时间的话,就不断执行某些任务。一旦这个属性等于0,就把任务分配到下一轮requestIdleCallback。

前面的示例代码之中,只要当前帧还有空闲时间,就不断调用doWorkIfNeeded方法。一旦没有空闲时间,但是任务还没有全执行,就分配到下一轮requestIdleCallback。

(2)didTimeout属性

deadline对象的 didTimeout 属性会返回一个布尔值,表示指定的时间是否过期。这意味着,如果回调函数由于指定时间过期而触发,那么你会得到两个结果。

  • timeRemaining方法返回0
  • didTimeout 属性等于 true

因此,如果回调函数执行了,无非是两种原因:当前帧有空闲时间,或者指定时间到了。

function myNonEssentialWork (deadline) {
  while ((deadline.timeRemaining() > 0 || deadline.didTimeout) && tasks.length > 0)
    doWorkIfNeeded();

  if (tasks.length > 0)
    requestIdleCallback(myNonEssentialWork);
}

requestIdleCallback(myNonEssentialWork, 5000);

上面代码确保了,doWorkIfNeeded 函数一定会在将来某个比较空闲的时间(或者在指定时间过期后)得到反复执行。

requestIdleCallback 是一个很新的函数,刚刚引入标准,目前只有Chrome支持,不过其他浏览器可以用垫片库

九、参考链接

(完)

1,711 Replies to “网页性能管理详解”

  1. I have noticed you don’t monetize your site, don’t waste your traffic,
    you can earn extra bucks every month because you’ve
    got hi quality content. If you want to know how to make extra $$$, search
    for: Mrdalekjd methods for $$$

  2. Thanks for your own hard work on this web page. Kim enjoys participating in investigation and it is obvious why. I notice all concerning the dynamic ways you give rewarding ideas by means of the web site and as well as cause participation from the others on the subject matter and my daughter is starting to learn a lot of things. Have fun with the rest of the year. You are conducting a fantastic job.
    rose 8

  3. Hey there just wanted to give you a brief heads up and let you know a few of the pictures aren’t loading properly. I’m not sure why but I think its a linking issue. I’ve tried it in two different internet browsers and both show the same results.
    air max 90

  4. Kaufen ohne rezept gunstig, legal in deutschland kaufen und filmtabletten beipackzettel, au?er online bestellen mit kreditkarte, online apotheke rezeptfrei. Generika gunstig kaufen auch in frankreich rezeptfrei, generika preisubersicht und rezeptfreie generika trotz wo kann ich rezeptfrei kaufen.
    kyrie irving shoes

  5. This makes both ends get their advantages.hxjqcrusher. Actually, there is nothing you can pay for them that can measure up to the benefitsthey’ll confer on your hotel business. Although this is not by far the most professional way to develop your films, I choose to dry my photos by just hanging them like these people were wet clothes. You need to look for a company which has a personable representative who cares about your needs.

  6. Long di?t?n?? m?ving ??m??ni?? are efficient in ?ff?ring l?ng di?t?n?? m?ving services.Follow Ralph D. Choosing an alternative ring means you can get something that fits your partner’s style, and doesn’t impose decades old design onto their appearance.<br >As far as the growth and development time is concerned, crusher industry belongs to a young sunrise industry.Did you know? A weight loss study reported in the Journal of the American Medical Association revealed that people who had a treadmill at home lost an average of four to eight pounds more than those who didn’t have treadmills.

  7. Thanks for your helpful post. In recent times, I have been able to understand that the symptoms of mesothelioma are caused by the particular build up of fluid between your lining in the lung and the chest muscles cavity. The infection may start in the chest vicinity and pass on to other areas of the body. Other symptoms of pleural mesothelioma cancer include weight-loss, severe breathing in trouble, vomiting, difficulty ingesting, and swelling of the neck and face areas. It ought to be noted that some people having the disease don’t experience any serious signs at all.
    adidas tubular shadow

  8. Thanks for discussing your ideas. I would also like to express that video games have been at any time evolving. Modern tools and enhancements have made it easier to create reasonable and active games. These kind of entertainment games were not really sensible when the concept was first being tried. Just like other forms of know-how, video games also have had to evolve as a result of many decades. This itself is testimony to the fast development of video games.
    adidas originals

  9. Great – I should definitely pronounce, impressed with your site. I had no trouble navigating through all tabs and related information ended up being truly simple to do to access. I recently found what I hoped for before you know it in the least. Quite unusual. Is likely to appreciate it for those who add forums or anything, web site theme . a tones way for your client to communicate. Nice task.
    ugg outlet

  10. An added important issue is that if you are a senior, travel insurance regarding pensioners is something you should really take into account. The older you are, greater at risk you are for allowing something poor happen to you while overseas. If you are not covered by some comprehensive insurance, you could have several serious challenges. Thanks for discussing your guidelines on this blog site.
    kevin durant shoes

  11. I actually wanted to write down a brief message in order to say thanks to you for all of the magnificent pointers you are showing at this site. My long internet lookup has finally been rewarded with useful know-how to talk about with my guests. I would believe that many of us readers actually are undoubtedly fortunate to be in a remarkable site with many marvellous individuals with useful tips and hints. I feel truly blessed to have encountered the web site and look forward to some more exciting times reading here. Thanks a lot once again for a lot of things.
    adidas pure boost

  12. What i do not realize is in reality how you are not actually much more neatly-preferred than you might be now. You’re so intelligent. You already know therefore considerably when it comes to this topic, produced me individually believe it from so many various angles. Its like men and women are not fascinated until it is something to do with Girl gaga! Your personal stuffs excellent. Always maintain it up!
    nike shoes

  13. One more important component is that if you are a senior citizen, travel insurance with regard to pensioners is something you should really take into account. The elderly you are, the harder at risk you are for permitting something bad happen to you while in most foreign countries. If you are certainly not covered by a few comprehensive insurance, you could have several serious problems. Thanks for revealing your good tips on this web site.
    balenciaga sneakers

  14. Preise deutschland, generika online kaufen und reines bestellen, au?er apotheke deutschland, once online kaufen. Kostenubernahme auch billig kaufen, preise apotheke deutschland und preiswert online trotz ohne rezept bestellen.
    ugg 5803

  15. I just want to tell you that I’m all new to blogging and actually loved your web-site. More than likely I’m want to bookmark your site . You surely come with fantastic well written articles. Many thanks for revealing your blog.
    Curry Shoes

  16. Bestellen erfahrung, generika per uberweisung kaufen und in osterreich verboten, au?er billig kaufen per uberweisung, rezeptfrei in deutschland. Preisunterschiede auch gunstig kaufen osterreich, generika preisubersicht und online bestellen ohne rezept schweiz trotz pille ohne rezept bestellen.
    adidas climacool

  17. I became honored to get a call from a friend when he found out the important ideas shared in your site. Examining your blog posting is a real brilliant experience. Thanks again for considering readers just like me, and I want for you the best of achievements as a professional in this surface area.
    adidas nmd

  18. One more thing. I do believe that there are a lot of travel insurance web sites of respected companies that let you enter your holiday details and get you the insurance quotes. You can also purchase the international travel cover policy on the web by using the credit card. Everything you need to do is usually to enter all travel details and you can start to see the plans side-by-side. Only find the package that suits your finances and needs after which use your credit card to buy that. Travel insurance on the web is a good way to check for a dependable company for international holiday insurance. Thanks for expressing your ideas.
    nike huarache

  19. One thing I want to say is that often before purchasing more laptop or computer memory, look into the machine into which it could well be installed. Should the machine is usually running Windows XP, for instance, the particular memory ceiling is 3.25GB. Applying above this would purely constitute any waste. Make certain that one’s motherboard can handle your upgrade amount, as well. Great blog post.
    yeezy boost 350

  20. They make tasks easier in that they effectively assist in handling of materials. In most case, people specialize in one operating one heavy machine such as Tischbohrwerk. This is one of the most reliable kinds of lock out there. Choosing an alternative ring means you can get something that fits your partner’s style, and doesn’t impose decades old design onto their appearance.The incorporation of nutrition programs in several fitness centers and sports facilities also support the worldwide concern for sports nutrition.

  21. Thanks for the guidelines shared on the blog. Something else I would like to convey is that losing weight is not exactly about going on a fad diet and trying to shed as much weight as you’re able in a couple of weeks. The most effective way to shed weight is by consuming it bit by bit and obeying some basic suggestions which can make it easier to make the most from the attempt to shed weight. You may understand and already be following some of these tips, nonetheless reinforcing awareness never hurts.
    adidas originals

  22. If a web design company does not want to understand your needs, how can they satisfy them?3) The ContactIf the company you are looking at has satisfied both of the above descriptions, it is time for you to contact them.If you are pondering what to wear for your ft and to appear glamorous in your social circle, UGG boots are your number one option. For instance, if it’s an electric company, try to ask if they provide uninterrupted service. If we focus back in the earlier days, it was hard to handle materials manually without heavy machines. Before many people were not overly conscious with what they were eating and the nutrients that the food provided.

  23. Owen said: “Cleveland need game.”Indeed, they rested for too long.In green, and the wizards to after the tiebreak, the beginning of the knight’s eastern conference finals first time has pushed the next Wednesday.
    kyire 3

  24. Thanks for the tips on credit repair on this blog. The things i would advice people would be to give up this mentality that they buy at this moment and pay later. As being a society all of us tend to repeat this for many things. This includes getaways, furniture, plus items we would like. However, it is advisable to separate your own wants from all the needs. If you are working to improve your credit rating score make some sacrifices. For example you may shop online to save money or you can look at second hand shops instead of high priced department stores pertaining to clothing.
    yeezy boost 350

  25. Thanks for your strategies. One thing we’ve noticed is always that banks in addition to financial institutions understand the spending practices of consumers and as well understand that most people max outside their credit cards around the vacations. They wisely take advantage of this fact and begin flooding your inbox along with snail-mail box along with hundreds of no interest APR card offers shortly when the holiday season comes to an end. Knowing that when you are like 98% of American community, you’ll hop at the possiblity to consolidate card debt and shift balances for 0 APR credit cards.
    kevin durant shoes

  26. The NBA playoffs now for today, have determined the warriors in the western conference and will compete for a spot in the finals quota, knight still don’t know who his opponent was.However, even in the face of the celtics or the wizards, presumably knight will be
    kobe bryant shoes

  27. The NBA playoffs now for today, have determined the warriors in the western conference and will compete for a spot in the finals quota, knight still don’t know who his opponent was.However, even in the face of the celtics or the wizards, presumably knight will be
    curry 4

  28. The NBA playoffs now for today, have determined the warriors in the western conference and will compete for a spot in the finals quota, knight still don’t know who his opponent was.However, even in the face of the celtics or the wizards, presumably knight will be
    curry 4

  29. Owen said: “Cleveland need game.”Indeed, they rested for too long.In green, and the wizards to after the tiebreak, the beginning of the knight’s eastern conference finals first time has pushed the next Wednesday.
    adidas ax2

  30. NBA players in addition to playing badly, and also an art cells, for two consecutive years in the NBA finals two teams join forces with the warriors and knight, but only two dancers, two teams played neck and neck, dancing is close, take a look at
    calvin klein

  31. Draft of the same year on the bottom rookie will be what?In general the draft should be able to blow the other party, who would have thought them took Owen on the 60th pick small Thomas in the same year, he turned out to be in the position of the challenger?
    nike air max 97

  32. Fantastic items from you, man. I have be mindful your stuff prior to and you are simply extremely excellent. I actually like what you have obtained right here, really like what you’re stating and the way by which you assert it. You make it enjoyable and you continue to care for to stay it wise. I can not wait to learn far more from you. This is actually a tremendous website.
    mbt shoes

  33. I think other web site proprietors should take this web site as an model, very clean and great user genial style and design, as well as the content. You’re an expert in this topic!

  34. Thanks for this glorious article. Yet another thing to mention is that the majority of digital cameras come equipped with the zoom lens that enables more or less of any scene to get included by means of ‘zooming’ in and out. These kind of changes in focus length are usually reflected from the viewfinder and on big display screen right at the back of the particular camera.

  35. I have to show my admiration for your kind-heartedness supporting persons that need help on your topic. Your special dedication to passing the message all around came to be pretty productive and have consistently allowed individuals just like me to achieve their desired goals. Your new interesting help denotes a lot a person like me and even further to my peers. Warm regards; from each one of us.

  36. Thanks for your handy post. As time passes, I have been able to understand that the particular symptoms of mesothelioma cancer are caused by the actual build up of fluid between your lining of the lung and the chest muscles cavity. The infection may start in the chest region and propagate to other body parts. Other symptoms of pleural mesothelioma include weight reduction, severe breathing in trouble, temperature, difficulty ingesting, and irritation of the neck and face areas. It needs to be noted some people having the disease never experience virtually any serious signs at all.

  37. Greetings from California! I’m bored to death at
    work so I decided to check out your website on my iphone during lunch break.
    I really like the info you provide here and can’t wait to take a look when I get home.
    I’m surprised at how quick your blog loaded on my phone ..

    I’m not even using WIFI, just 3G .. Anyhow, awesome blog!

  38. Attractive section of content. I simply stumbled upon your web site and in accession capital to assert that I acquire actually loved account your blog posts.
    Anyway I’ll be subscribing to your augment or even I fulfillment you get admission to persistently fast.

  39. Excellent post. I was checking continuously this blog and I am impressed!
    Extremely useful info particularly the last part 🙂
    I care for such information a lot. I was seeking
    this certain info for a long time. Thank you and best of luck.