Talk about the front-end performance optimization CRP

What is CRP?

CRPAlso known as the critical rendering path, to quote MDNits explanation:

The critical rendering path refers to the sequence of steps in which the browser converts HTML, CSS, and JavaScript into pixels on the screen. Optimizing the critical rendering path can improve rendering performance. The critical rendering path includes Document Object Model (DOM), CSS Object Model (CSSOM), rendering tree and layout.

Optimizing the critical rendering path can improve the first screen rendering time. Understanding and optimizing the critical rendering path is essential to ensure that reflow and redraw can be performed at 60 frames per second, to ensure high-performance user interaction, and to avoid meaningless rendering.

How to combine CRPperformance optimization?

I think everyone is no stranger to performance optimization, whether it is a normal job or an interview, it is a common topic.

If we only talk about some points in general, I think it is not very rigorous.

Today we combine a very classic interview question: let's 从输入URL到页面展示,这中间发生了什么?talk in depth from some of the links 前端性能优化 CRP.

From entering the URL to displaying the page, what happened?

I don’t need to say more about the classic level of this question. Here I use a picture to sort out its general process: This process can be roughly described as follows:

1, URI analysis

2. DNS resolution (DNS server)

3. TCP three-way handshake (establish a connection channel between client and server)

4. Send HTTP request

5. Server processing and response

6. TCP waved four times (close the connection between client and server)

7. Browser parsing and rendering

8. The page is loaded

In this article, I will explain the performance optimization from the browser rendering process, caching, and DNS optimization.

Browser rendering process

Build the DOM tree

DOMThe general process of building a tree is summarized as the following figure:

We take the following piece of code as an example for analysis:

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link href="style.css" rel="stylesheet">
    <title>构建DOM树</title>
  </head>
  <body>
    <p>森林</p>
    <div>之晨</div>
  </body>
</html>

First, the browser reads from disk or network HTMLraw bytes, and coded according to the specified file to convert them into characters.

Word will then be converted to the byte stream Tokenin Token(i.e. token) generated at the same time, another process will also consume the token and converted into HTML headthe node object, indicate the start and end of the token between nodes relationship.

When all the tokens are consumed, it is converted to DOM(Document Object Model).

The final DOMstructure is as follows:

Build the CSSOM tree

DOMThe tree is built, and the next step is CSSOMto build the tree.

Similar to HTMLthe conversion, the browser will identify the CSScorrect tokens and then convert these tokens into CSSnodes.

The child node will inherit the style rules of the parent node, which corresponds to the cascading rules and cascading style sheets.

DOMThe general process of building a tree can be summarized as the following figure:

We use the above as HTMLan example here , assuming it has the following css:

body {
  font-size: 16px;
}
p {
  font-weight: bold;
}
div {
  color: orange;
}

Then the finally constructed CSSOMtree is as follows:

With DOMand CSSOM, you can then synthesize the layout tree (Render Tree) up.

Build the render tree

And so on DOMand CSSOMthen you have to build good layout rendering engine will be constructed tree. Layout tree structure is substantially replicated DOMtree structure, except that DOMtrees do not show those elements are filtered out, such as the display:noneelement attributes, headlabels, scripttags and the like.

After copying a good basic layout tree structure, the rendering engine for the corresponding DOMselect the style information corresponding to the elements, this process is the style computing.

Style calculation

Object style calculation is to calculate the DOMnode specific style of each element, this stage can be divided into three steps to complete.

Convert CSS into a structure that the browser can understand

And HTMLfiles, the browser is not directly understand plain text CSSstyle, so when rendering engine receives a CSStext, performs a conversion operation, the CSStext conversion structure browser understandable - styleSheets.

Convert the attribute values ​​in the style sheet to standardize

Now that we have converted the existing CSS text into a structure that the browser can understand, the next step is to standardize its attribute values.

What is attribute value standardization? Let's look at this paragraph CSS:

body {
  font-size: 2em;
}
div {
  font-weight: bold;
}
div {
  color: red;
}

Can see the above CSStext, there are many property values, such as 2em, bold, red, values of these types are not easily understood by the rendering engine, it is necessary to convert all the values to be readily understood by the rendering engine, the normalized value is calculated, the process is Standardization of attribute values.

What does the normalized attribute value look like?

As you can see from the figure, it 2emwas parsed into 32px, boldparsed into 700, and redparsed into rgb(255,0,0)...

Calculate the specific style of each node in the DOM tree

Now-style property has been standardized, then you need to calculate the DOMtree in the style attributes of each node, and how to calculate it?

This involves two points: the 继承规则sum of CSS 层叠规则.

Since this is not the focus of this article, I will briefly explain:

  • CSSInheritance is that each DOMnode contains a parent style

  • Is laminated CSSto a basic feature, it is a property value defines how to merge algorithm from multiple sources. It CSSis the core, CSSthe full name "Cascading Style Sheets" precisely to emphasize this point.

After the style calculation is completed, the rendering engine also needs to calculate the geometric position of each element in the layout tree. This process is to calculate the layout.

Calculation layout

Now, we have DOMtrees and DOMstyle elements in the tree, but not enough to display the page, because we do not know DOMthe geometric position of the element of information. So then you need to calculate the DOMgeometric position of the tree visible elements, we put this calculation is called 布局.

draw

The construction of the final layout tree is completed through style calculation and layout calculation. After that, it's time for subsequent drawing operations.

At this point, the rendering process of the browser is basically over, sorted out through the following picture:

At this point, we have sorted out the complete process of browser parsing and rendering, so where can we optimize performance?

Optimization points that can be done from the browser's rendering process

Usually a page has three stages: loading stage, interactive stage and closing stage.

  • Loading phase, is from the request to render a complete page of the process, the main factors affecting this stage there is a network and JavaScriptscripts.

  • Interactive stage, notably the completion of the integration process from page to load user interaction, the main factors affecting this stage is the JavaScriptscript.

  • In the closing phase, it is mainly the cleaning operations performed by the page after the user issues a closing instruction.

Here we need to focus on 加载阶段and 交互阶段, because the factors that affect our experience are mainly in these two stages, let's analyze in detail one by one.

Loading phase

Let's first analyze how to systematically optimize the page in the loading phase and look at a typical rendering pipeline, as shown in the following figure:

By analyzing the browser rendering process on the face of our knowledge JavaScript, the first request of HTMLthe resource file, CSSthe file is blocked for the first time will be rendered, because the build DOMprocess requires HTMLand JavaScriptdocuments, during the construction of the render tree need to use the CSSfile.

These resources that can block the first rendering of a web page are called 关键资源. Based on key resources, we can continue to refine three core factors that affect the first rendering of the page:

  • 关键资源个数. The more key resources, the longer the first page load time.

  • 关键资源大小. Under normal circumstances, the smaller the content of all key resources, the shorter the download time of the entire resource, and the shorter the time blocking rendering.

  • 请求关键资源需要多少个RTT(Round Trip Time). RTTIt is an important performance indicator in the network. It represents the total time delay experienced from the sending end of sending data to the receiving end of the confirmation from the receiving end.

After understanding several core factors that affect the loading process, then we can systematically consider the optimization plan. The overall optimization principle is 减少关键资源个数, 降低关键资源大小, 降低关键资源的 RTT 次数:

  • How to reduce the number of key resources? One way is to JavaScriptand CSSforms into inline, such as the map JavaScriptand CSS, if inline mode are changed, then the reduced number of critical resources of three to one. Another way, if the JavaScriptcode is not DOMor CSSOMoperations, it can be changed syncor deferproperties

  • How to reduce the size of critical resources? Can compress CSSand JavaScriptresources, remove HTML, CSS, JavaScriptfile content in some of the comments

  • How to reduce the key resources RTTthe number? This can be achieved by reducing the number of key resources and reducing the size of key resources. In addition, it can also be used CDNto reduce a time RTTduration.

Interactive phase

Next, let's talk about the interactive phase after the page is loaded and how to optimize it.

Let's first take a look at the rendering pipeline in the interactive phase: in fact, there are roughly the following points that can be optimized:

  • 避免DOM的回流. That is, try to avoid 重排and 重绘operate.

  • 减少 JavaScript 脚本执行时间. Sometimes JavaScriptthe execution time of a function may be several hundred milliseconds, which seriously occupies the time of the main thread to perform other rendering tasks. In view of this situation, we can adopt the following two strategies:

    • One is to decompose the function executed once into multiple tasks, so that each execution time should not be too long.

    • The other is to adopt Web Workers.

  • DOM操作相关的优化. Browsers 渲染引擎and JS引擎so when use JSoperation DOM, the two engines to each other through an interface "communication" and therefore every operation DOM(including the only access DOMproperties), should be resolved between the engine overhead is often said to be reduced DOM manipulation. In summary, the following points:

    • Cache some calculated properties, such as let left = el.offsetLeft.

    • By DOMthe classto centralize change the style, rather than styleto modify a bar.

    • Separate read and write operations. Modern browsers have a rendering queue mechanism.

    • DOMThe era of abandoning traditional operations , based vue/reacton virtual domthe framework adopted by others

  • 合理利用 CSS 合成动画. Synthetic animation is performed directly on the synthetic thread, this layout and operation, such as drawing executed on the main thread different, if the main thread JavaScriptor some layout tasks occupation, CSSanimation was still able to continue. So try to make good use of CSSsynthetic animation, if we make CSSthe animation, as far as possible to CSSoperate.

  • CSS选择器优化. We know that the CSS引擎search is matched from right to left. So based on this, there are the following optimization solutions:

    • Try not to use wildcards

    • Use tag selectors sparingly

    • Use attribute inheritance as much as possible

  • CSS属性优化. When the browser rendering images, CSSthe cost is calculated properties, some properties require a lot of computing browser, belonging to the expensive properties ( box-shadows, border-radius, transforms, filters, opcity, :nth-child, etc.), these attributes often used in everyday development, so not to say Don't use these attributes, but in development, if there are other simple and feasible solutions, you can give preference to solutions without expensive attributes.

  • 避免频繁的垃圾回收. We know that JavaScriptusing automatic garbage collection, if you create a temporary object in some function frequently, then the garbage collector will go to the garbage collection policy frequently. In this way, when the garbage collection operation occurs, it will occupy the main thread, which will affect the execution of other tasks, and in serious cases, it will make the user feel that the frame is dropped and not smooth.

Cache

Caching can be said to be a simple and efficient optimization method in performance optimization. An excellent caching strategy can shorten the distance of web page request resources, reduce latency, and because cached files can be reused, it can also reduce bandwidth and reduce network load. The figure below is the search flow chart of browser cache : there are still many knowledge points related to browser cache. Here I have compiled a picture: For a detailed introduction to browser cache, you can refer to my previous article , here I won't go into details.

DNS related optimization

DNSFull name Domain Name System. It is the "address book" of the Internet, which records the ipmapping between domain names and actual addresses. Every time we visit a website, we must DNSquery the server of the website through servers at all levels ip, and then we can access the server.

DNSRelated optimization generally involves two points: browser DNScaching and DNSpre-parse.

DNSCache

A picture is worth a thousand words:

  • The browser will first check the browser cache (the browser cache has a size and time limit). If the time is too long, it may cause the IPaddress to change and fail to resolve the correct IPaddress. If it is too short, the browser will repeatedly resolve the domain name, usually a few minutes.

  • If the browser cache does not have a corresponding domain name, it will look in the operating system cache.

  • If it has not been found, the domain name will be sent to the domain name server (usually provided by Internet providers, such as China Telecom, China Unicom), and it can generally be found on the domain name server in the region.

  • Of course, the local domain name server may not be found either, and the local domain name server will start recursive search.

Generally speaking, browsers DNSrequire parsing 20-120ms, so there DNSare few optimizations for parsing. However, there is a scenario where there are many pictures on the website under different domain names. If the domain name that may be used after the login page is resolved in advance, the resolution result will be cached, which shortens the DNSresolution time and improves the overall website access Speed ​​up, that's it DNS预解析.

DNSPre-analysis

Take a look at DNS预解析the definition of MDN :

X-DNS-Prefetch-ControlThe head control the browser's DNSpre-reading function. DNSPre-reading is an initiative to make the browser perform domain name resolution function, and its scope includes all of the linked document, whether it is pictures, CSSand or JavaScriptother users can click URL.

Because the pre-reading will be performed in the background, so DNSit may have been resolved before the link corresponding things appear completed. This can reduce the delay when users click on the link.

Let's briefly look at how to do it here DNS预解析:

  • Add in the header of the page so that the browser will pre-parse the entire page

<meta http-equiv="x-dns-prefetch-control" content="on">
  • Manually add the domain name to be resolved through the link tag, for example:

<link rel="dns-prefetch" href="//img10.360buyimg.com"/>

reference

Li Bing "Browser Working Principle and Practice"

"Watching and forwarding" is the greatest support

Guess you like

Origin blog.csdn.net/liuyan19891230/article/details/108211818