What is CRP?
CRP
Also known as the critical rendering path, to quote MDN
its 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 CRP
performance 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
DOM
The 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 HTML
raw bytes, and coded according to the specified file to convert them into characters.
Word will then be converted to the byte stream Token
in Token
(i.e. token) generated at the same time, another process will also consume the token and converted into HTML head
the 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 DOM
structure is as follows:
Build the CSSOM tree
DOM
The tree is built, and the next step is CSSOM
to build the tree.
Similar to HTML
the conversion, the browser will identify the CSS
correct tokens and then convert these tokens into CSS
nodes.
❝The child node will inherit the style rules of the parent node, which corresponds to the cascading rules and cascading style sheets.
❞
DOM
The general process of building a tree can be summarized as the following figure:
We use the above as HTML
an example here , assuming it has the following css:
body {
font-size: 16px;
}
p {
font-weight: bold;
}
div {
color: orange;
}
Then the finally constructed CSSOM
tree is as follows:
With DOM
and CSSOM
, you can then synthesize the layout tree (Render Tree) up.
Build the render tree
And so on DOM
and CSSOM
then you have to build good layout rendering engine will be constructed tree. Layout tree structure is substantially replicated DOM
tree structure, except that DOM
trees do not show those elements are filtered out, such as the display:none
element attributes, head
labels, script
tags and the like.
After copying a good basic layout tree structure, the rendering engine for the corresponding DOM
select the style information corresponding to the elements, this process is the style computing.
Style calculation
Object style calculation is to calculate the DOM
node 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 HTML
files, the browser is not directly understand plain text CSS
style, so when rendering engine receives a CSS
text, performs a conversion operation, the CSS
text 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 CSS
text, 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 2em
was parsed into 32px
, bold
parsed into 700
, and red
parsed 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 DOM
tree 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:
CSS
Inheritance is that eachDOM
node contains a parent styleIs laminated
CSS
to a basic feature, it is a property value defines how to merge algorithm from multiple sources. ItCSS
is the core,CSS
the 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 DOM
trees and DOM
style elements in the tree, but not enough to display the page, because we do not know DOM
the geometric position of the element of information. So then you need to calculate the DOM
geometric 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
JavaScript
scripts.Interactive stage, notably the completion of the integration process from page to load user interaction, the main factors affecting this stage is the
JavaScript
script.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 HTML
the resource file, CSS
the file is blocked for the first time will be rendered, because the build DOM
process requires HTML
and JavaScript
documents, during the construction of the render tree need to use the CSS
file.
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)
.RTT
It 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
JavaScript
andCSS
forms into inline, such as the mapJavaScript
andCSS
, if inline mode are changed, then the reduced number of critical resources of three to one. Another way, if theJavaScript
code is notDOM
orCSSOM
operations, it can be changedsync
ordefer
propertiesHow to reduce the size of critical resources? Can compress
CSS
andJavaScript
resources, removeHTML
,CSS
,JavaScript
file content in some of the commentsHow to reduce the key resources
RTT
the 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 usedCDN
to reduce a timeRTT
duration.
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 脚本执行时间
. SometimesJavaScript
the 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渲染引擎
andJS引擎
so when useJS
operationDOM
, the two engines to each other through an interface "communication" and therefore every operationDOM
(including the only accessDOM
properties), 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
DOM
theclass
to centralize change the style, rather thanstyle
to modify a bar.Separate read and write operations. Modern browsers have a rendering queue mechanism.
DOM
The era of abandoning traditional operations , basedvue/react
onvirtual dom
the 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 threadJavaScript
or some layout tasks occupation,CSS
animation was still able to continue. So try to make good use ofCSS
synthetic animation, if we makeCSS
the animation, as far as possible toCSS
operate.CSS选择器优化
. We know that theCSS引擎
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,CSS
the 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 thatJavaScript
using 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
DNS
Full name Domain Name System
. It is the "address book" of the Internet, which records the ip
mapping between domain names and actual addresses. Every time we visit a website, we must DNS
query the server of the website through servers at all levels ip
, and then we can access the server.
DNS
Related optimization generally involves two points: browser DNS
caching and DNS
pre-parse.
DNS
Cache
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
IP
address to change and fail to resolve the correctIP
address. 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 DNS
require parsing 20-120ms
, so there DNS
are 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 DNS
resolution time and improves the overall website access Speed up, that's it DNS预解析
.
DNS
Pre-analysis
Take a look at DNS预解析
the definition of MDN :
❝❞
X-DNS-Prefetch-Control
The head control the browser'sDNS
pre-reading function.DNS
Pre-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,CSS
and orJavaScript
other users can clickURL
.
Because the pre-reading will be performed in the background, so DNS
it 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