authors are vetted experts in their fields 和 write on topics in which they have demonstrated experience. All of our content is peer reviewed 和 validated by Toptal experts in the same field.
Ilya基诺夫
验证专家 在工程
11 的经验

Ilya is an accomplished engineer with over five years of experience working on remote 和 onsite teams, 以及领导其他开发者.

专业知识

分享

Does your web page’s rendering performance meet today’s st和ards? Rendering is the process of translating a server’s response into the picture the browser “paints” when a user visits a website. A bad rendering performance can translate into a relatively high bounce rate.

There are different server responses which determine whether or 不 a page is rendered. 在本文中, we are going to focus on the initial render of the web page, which starts with parsing HTML (provided the browser has successfully received HTML as the server’s response). We’ll explore the things that can lead to high rendering times, 和 how to fix them.

关键渲染路径

The critical rendering path (CRP) is the process your browser goes through to convert the code into displayable pixels on your screen. 它有几个阶段, some of which could be performed in parallel to save time, 但有些部分必须按顺序完成. 这是可视化的:

关键渲染路径

首先, once the browser gets the response, it starts parsing it. When it encounters a dependency, it tries to download it.

如果它是一个样式表文件, the browser will have to parse it completely before rendering the page, 这就是为什么 CSS被称为渲染阻塞.

If it’s a script, the browser has to: stop parsing, download the script, 和 run it. 只有在此之后,它才能继续解析, because JavaScript programs can alter the contents of a web page (HTML, 特别是). 这就是为什么 JS称为解析器阻塞.

一旦所有解析完成, the browser has the Document Object Model (DOM) 和 Cascading Style Sheets Object Model (CSSOM) built. 将它们组合在一起就得到了渲染树. The non-displayed parts of the page don’t make it into the Render Tree, because it only contains the data necessary to draw the page.

The penultimate step is to translate the Render Tree into Layout. 这个阶段也被称为回流. That’s where every position of every Render Tree’s node, as well as its size, gets calculated.

最后,最后一步是油漆. It involves literally coloring the pixels according to the data the browser has calculated during the previous stages.

你们可以猜到, the process of website performance optimization involves changes to the website that reduce:

  • 必须传输的数据量
  • The number of resources the browser has to download (especially the blocking ones)
  • CRP的长度

进一步, 我们将深入研究它是如何完成的细节, 但首先, 有一条重要的规则需要遵守.

如何衡量绩效

An important rule of optimization is: Measure first, optimize as needed. Most browsers’ developer tools have a tab called 表演这就是测量发生的地方. When optimizing for the fas测试 initial (first) render, the most important thing to look at is the time of the following events:

  • 第一次油漆
  • 第一个内容油漆
  • 第一次有意义的绘画

Here, “Paint” means successful render of a page, the last stage in the critical rendering path. A few renders may happen one after a不her because browsers try to display something ASAP 和 update later.

除了渲染时间, there are other things to take into account—most importantly, how many blocking resources are used 和 how long it takes to download them. This information is found in the 表演 tab after the measurements are made.

性能优化策略

根据我们上面学到的, there are three main strategies for website performance optimization:

  1. Minimizing the amount of data to be transferred over the wire,
  2. Reducing the total number of resources to be transferred over the wire, 和
  3. 缩短关键渲染路径

1. 尽量减少要传输的数据量

首先, 移除所有未使用的部件, 例如JavaScript中不可访问的函数, styles with selectors that never match any element, 以及永远隐藏在CSS中的HTML标签. 其次,删除所有重复项.

Then, I recommend putting an automatic process of minification in place. 例如, it should remove all the comments from what your back end is serving (but 不 the source code) 和 every character that bears no additional information (such as whitespace characters in JS).

After this is done, what we are left with can be as text. It means we can safely apply a compressing algorithm such as GZIP (which most browsers underst和).

最后是缓存. It won’t help the first time a browser renders the page, but it’ll save a lot on subsequent visits. It is crucial to keep two things in mind, though:

  • If you use a CDN, make sure caching is supported 和 properly set there.
  • Instead of waiting for the resources’ expiration date to come, you might want to have a way to update it earlier from your side. Embed files’ “finger打印s” into their URLs to be able to 本地缓存无效.

当然, caching policies should be defined per resource. 有些人可能很少改变或根本不会改变. 其他的变化更快. Some contain sensitive information, others could be considered public. 使用 “私人”指令 以防止cdn缓存私人数据.

优化网页图像也可以做到, although image requests don’t block either parsing or rendering.

2. 减少关键资源的总数

“Critical” refers only to resources needed for the web page to render properly. 因此, we can skip all the styles that are 不 involved in the process directly. 还有所有的剧本.

样式表

In order to tell the browser that particular CSS files are 不 required, we should set 媒体 attributes to all the links referencing stylesheets. With this approach, the browser will only treat the resources that match the current 媒体 (设备类型, 屏幕尺寸), while lowering the priority of all the other stylesheets (they will be processed anyway, 但不是作为关键渲染路径的一部分). 例如,如果添加 媒体= "打印" 属性于 style tag that’s referencing the styles for 打印ing out the page, these styles won’t interfere with your critical rendering path when 媒体 isn’t 打印 (i.e.,当在浏览器中显示页面时).

To further improve the process, you can also make some of the styles inlined. This saves us at least one roundtrip to the server that would have otherwise been required to get the stylesheet.

脚本

As mentioned above, scripts are parser blocking because they can alter DOM 和 CSSOM. 因此,脚本做 alter them should 不 be block parsing, thus saving us time.

In order to implement that, all script tags have to be marked with attributes—either 异步 or 推迟.

标有 异步 do 不 block the DOM construction or CSSOM, as they can be executed before CSSOM is built. Keep in mind, though, that inline scripts will block CSSOM anyway unless you put them above CSS.

相比之下,标记为 推迟 会在页面加载结束时进行评估吗. 因此, they shouldn’t affect the document (otherwise, it will trigger a re-render).

换句话说,用 推迟, the script isn’t executed until after the page load event is fired, whereas 异步 lets the script run in the background while the document is being parsed.

3. 缩短关键渲染路径长度

Finally, the CRP length should be shortened to the possible minimum. In part, the approaches described above will do that.

Media queries as attributes for the style tags will reduce the total count of resources that have to be downloaded. 脚本标签属性 推迟异步 will prevent the corresponding scripts from blocking the parsing.

缩小, 压缩, 和 archiving resources with GZIP will reduce the size of the transferred data (thereby reducing the data transfer time as well).

Inlining some styles 和 scripts can reduce the number of roundtrips between the browser 和 the server.

What we haven’t discussed yet is the option to rearrange the code among the files. According to the la测试 idea of best performance, the first thing a website should do fas测试 is to display ATF content. ATF代表上面. This is the area that’s visible right away, without scrolling. 因此, it is best to rearrange everything related to rendering it in a way that the required styles 和 scripts are loaded first, with everything else stopping - neither parsing nor rendering. And always remember to measure before 和 after you make the change.

Conclusion: 优化 Encompasses Your Entire Stack

总之, website performance optimization incorporates all aspects of your site response, 比如缓存, 设置CDN, 重构, 资源优化等, 然而,所有这些都可以逐步完成. 作为一个 web开发人员, 你应该把这篇文章作为参考, 和 always remember to measure performance before 和 after your experiments.

Browser developers do their best to optimize the website performance for every page you visit, which is why browsers usually implement the so-called “pre-loader.” This part of the programs scans ahead of a resource you’ve requested in HTML in order to make multiple requests at a time 和 have them run in parallel. This is why it is better to keep style tags close to each other in HTML (line-wise), 以及脚本标签.

此外, try to batch the updates to HTML in order to avoid multiple layout events, which are triggered 不 only by a change in DOM or CSSOM but also by a device orientation change 和 a window resize.

有用的资源和进一步阅读:

了解基本知识

  • 什么是网站优化?

    网络site optimization is the process of analyzing a website 和 introducing changes to make it load faster 和 perform better. 测量是这个过程的关键部分, 没有他们, there is no way to decide if a particular change made things better or worse.

  • 我如何检查我的网站性能?

    Try using online tools such as Google’s PageSpeed见解. You could also use your browser in “Private Browsing” mode to load the site without having any of the data cached locally. Some browsers also allow you to use throttling, which helps you simulate slow connection speed.

  • 什么是网站速度??

    网络site speed can be defined as the average time it takes for a website to load. 另外, 它可能是指每秒的帧数, 特别是在计算量大的操作中.

  • 网站加载速度应该有多快?

    最好能在一秒内装好. 当然, the time until the first meaningful paint matters more than the total loading time, as long as it keeps the user busy with the content.

  • 渲染引擎的功能是什么?

    在浏览器的上下文中, a rendering engine is a piece of software that’s responsible for drawing data in the browser window. See 关键渲染路径 above to get the details.

  • 什么是渲染阻塞?

    Render blocking is what the browser has to do while parsing stylesheet files because it can不 render the page until all the referenced stylesheet files are parsed.

聘请Toptal这方面的专家.
现在雇佣
Ilya基诺夫

Ilya基诺夫

验证专家 在工程
11 的经验

莫斯科,俄罗斯

2019年9月6日成为会员

作者简介

Ilya is an accomplished engineer with over five years of experience working on remote 和 onsite teams, 以及领导其他开发者.

authors are vetted experts in their fields 和 write on topics in which they have demonstrated experience. All of our content is peer reviewed 和 validated by Toptal experts in the same field.

专业知识

世界级的文章,每周发一次.

订阅意味着同意我们的 隐私政策

世界级的文章,每周发一次.

订阅意味着同意我们的 隐私政策

Toptal开发者

加入总冠军® 社区.