Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the front-end performance optimization CRP

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to understand the front-end performance optimization CRP". In the daily operation, I believe many people have doubts about how to understand the front-end performance optimization CRP. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts of "how to understand the front-end performance optimization CRP". Next, please follow the editor to study!

What is CRP?

CRP, also known as critical rendering path, quotes MDN's explanation of it:

The critical rendering path is the order of steps in which browsers convert HTML, CSS, and JavaScript into pixels on the screen. Optimizing critical rendering paths can improve rendering performance. The key rendering path includes Document Object Model (DOM), CSS Object Model (CSSOM), render tree, and layout.

Optimizing critical rendering paths can improve the rendering time of the first screen. Understanding and optimizing critical rendering paths is critical to ensuring 60 frames per second for reflow and redrawing, ensuring high-performance user interaction, and avoiding meaningless rendering.

How to optimize performance with CRP?

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

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

Today we combine a very classic interview question: from typing URL to page presentation, what happened? From some of these links, let's talk in depth about the front-end performance optimization CRP.

What happens in between, from typing URL to page presentation?

There must be no need for me to say more about the classic degree of this question. Here I use a picture to sort out its general process:

This process can be roughly described as follows:

URI parsing

DNS resolution (DNS server)

TCP three-way handshake (establishing a connection channel between the client and the server)

Send HTTP request

Server processing and response

TCP waves four times (closes the connection between the client and the server)

Browser parsing and rendering

Page loading completed

In this article, I will explain the performance optimization from the aspects of browser rendering process, cache, DNS optimization and so on.

Browser render proc

1. Build a DOM tree

The general process of building a DOM tree is summarized as follows:

Let's take the following code as an example:

Build a DOM tree

Forest

In the morning

First, the browser reads the HTML raw bytes from disk or network and converts them into characters according to the specified encoding of the file.

Then the byte stream is converted to Token through a word splitter, and while the Token (that is, tokens) is generated, another process consumes these tokens and converts them to node objects such as HTML head. The start and end tokens indicate the relationship between nodes.

When all tokens are consumed, they are converted to DOM (document object Model).

The final DOM structure is as follows:

two。 Build a CSSOM tree

The DOM tree is built, and then the CSSOM tree is built.

Similar to the conversion of HTML, the browser recognizes the correct tokens of the CSS and then converts those tokens into CSS nodes.

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

The general process of building a DOM tree can be sorted out as follows:

Let's take the above HTML as an example, assuming that it has the following css:

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

Then the final CSSOM tree is as follows:

With DOM and CSSOM, you can then synthesize the layout tree (Render Tree).

3. Build render Tr

After DOM and CSSOM are built, the rendering engine constructs the layout tree. The structure of the layout tree is basically to copy the structure of the DOM tree, the difference is that those elements in the DOM tree that do not need to be displayed will be filtered out, such as display:none attribute elements, head tags, script tags and so on.

After copying the basic layout tree structure, the rendering engine selects the corresponding style information for the corresponding DOM element, which is called style calculation.

4. Style calculation

The purpose of style calculation is to calculate the specific style of each element in the DOM node, which can be divided into three steps.

(1) convert CSS into a structure that browsers can understand

Like HTML files, browsers cannot directly understand the CSS style of these plain text, so when the rendering engine receives CSS text, it performs a conversion operation to convert CSS text into a structure that browsers can understand-styleSheets.

(2) convert the attribute values in the stylesheet to standardize them

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

What is the standardization of attribute values? Let's take a look at a CSS like this:

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

You can see that there are many attribute values in the above CSS text, such as 2em, bold, and red. These types of values are not easily understood by the rendering engine, so you need to convert all values into standardized calculated values that are easy for the rendering engine to understand. This process is to standardize the attribute values.

What does the standardized attribute value look like?

As you can see from the figure, 2em is parsed into 32px, bold, 700, red, and rgb.

(3) calculate the specific style of each node in the DOM tree

Now that the style attributes have been standardized, you need to calculate the style attributes for each node in the DOM tree. How do you calculate them?

This involves two points: CSS's inheritance rules and cascading rules.

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

CSS inheritance is the style in which each DOM node contains a parent node.

Cascading is a basic feature of CSS, an algorithm that defines how to merge attribute values from multiple sources. It is at the core of CSS, and the full name of CSS, cascading style sheets, emphasizes this point.

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

5. Computational layout

Now, we have the style of the elements in the DOM tree and the DOM tree, but this is not enough to display the page, because we do not yet know the geometric location information of the DOM element. Then we need to calculate the geometric position of the visible elements in the DOM tree, which we call layout.

6. 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 almost over. Comb through the following image:

So far, we have sorted out the complete process of browser parsing and rendering, so where can we do performance optimization?

The optimization points that can be made from the rendering process of the browser

Usually a page has three phases: the load phase, the interaction phase, and the close phase.

The loading phase, which refers to the process from issuing the request to rendering the complete page, is mainly affected by the network and JavaScript scripts.

The interaction stage is mainly the integration process from page loading to user interaction, and the main factor affecting this stage is the JavaScript script.

The shutdown phase is mainly some clean-up operations done by the page after the user issues the shutdown command.

Here we need to focus on the loading phase and the interaction phase, because the factors that affect our experience are mainly in these two stages, so let's analyze them in detail one by one.

1. Loading phase

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

Through the analysis of the browser rendering process above, we know that JavaScript, the first requested HTML resource file, and the CSS file will block the first rendering, because the HTML and JavaScript files are needed in the process of building DOM, and the CSS file is needed in the process of constructing the rendering tree.

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

Number of key resources. The more critical resources, the longer the first page will load.

Critical resource size. In general, the smaller the content of all critical resources, the shorter the download time for the entire resource, and the less time it takes to block rendering.

How many RTT (Round Trip Time) are required to request critical resources. RTT is an important performance indicator in the network, which represents the total delay from the time the sender sends the data to the acknowledgment that the sender receives from the receiver.

Now that we understand several core factors that affect the loading process, we can then systematically consider the optimization scheme. The overall optimization principle is to reduce the number of critical resources, reduce the size of critical resources, and reduce the number of RTT of critical resources:

How to reduce the number of critical resources? One way is to change JavaScript and CSS to inline form, such as JavaScript and CSS in the figure above, if both are changed to inline mode, then the number of key resources will be reduced from 3 to 1. On the other hand, if the JavaScript code does not have the operation of DOM or CSSOM, it can be changed to the sync or defer attribute

How to reduce the size of critical resources? You can compress CSS and JavaScript resources and remove some comments from HTML, CSS, and JavaScript files

How to reduce the number of critical resource RTT? This can be achieved by reducing the number of key resources and reducing the size of key resources. In addition, you can use CDN to reduce the length of each RTT.

two。 Interaction stage

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

First, let's take a look at the rendering pipeline in the interactive phase:

In fact, this piece can be optimized in the following ways:

(1) avoid the reflux of DOM. That is, try to avoid rearranging and redrawing operations.

(2) reduce the execution time of JavaScript scripts. Sometimes the execution time of a JavaScript function may be hundreds of milliseconds, which seriously takes up the time of the main thread to perform other rendering tasks. In response to this situation, we can adopt the following two strategies:

One is to decompose the function executed at one time into multiple tasks, so that each execution time is not too long.

The other is to use Web Workers.

(3) Optimization related to DOM operation. The browser has a rendering engine and a JS engine, so when using JS to operate DOM, the two engines "communicate" with each other through the interface, so every time you operate DOM (including just accessing the properties of DOM), you have to parse between engines, so it is often said to reduce DOM operations. To sum up, there are the following points:

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

Change the style centrally through DOM's class, rather than changing it one by one through style.

Separate read and write operations. Modern browsers have a mechanism for rendering queues.

The era of abandoning the traditional operation of DOM, based on vue/react and other frameworks that adopt virtual dom

(4) make rational use of CSS to synthesize animation. Compositing animation is executed directly on the compositing thread, which is different from the layout, drawing and other operations performed on the main thread. If the main thread is occupied by JavaScript or some layout tasks, CSS animation can still be executed. So try to make good use of CSS composite animation, if you can let CSS handle the animation, try to let CSS to operate.

(5) CSS selector optimization. We know that CSS engine lookups match from right to left. Therefore, based on this, there are several optimization schemes:

Try not to use wildcards

Use less tag selectors

Make use of attribute inheritance as much as possible

(6) CSS attribute optimization. When the browser draws the image, the calculation of CSS also consumes performance. Some attributes need a lot of calculation by the browser, and they belong to expensive attributes (box-shadows, border-radius, transforms, filters, opcity,: nth-child, etc.). These attributes are often used in daily development, so it is not to say that you do not use these attributes, but in development, if there are other simple and feasible solutions, you can give priority to those without expensive attributes.

(7) avoid frequent garbage collection. We know that JavaScript uses an automatic garbage collection mechanism, and if temporary objects are frequently created in some functions, the garbage collector will also frequently execute the garbage collection policy. In this way, when the garbage collection operation occurs, it will occupy the main thread, thus affecting the execution of other tasks, and in serious cases, it will make the user feel that the frame is dropped and not smooth.

Caching

Caching can be said to be a simple and efficient way of performance optimization. An excellent caching strategy can shorten the distance of web page request resources, reduce latency, and because cache files can be reused, it can also reduce bandwidth and network load. The following figure shows the lookup flowchart of the browser cache:

There are still a lot of knowledge points related to browser cache. Here I have a picture:

DNS related optimization

DNS is called Domain Name System. It is the "address book" of the Internet, which records the mapping between domain names and actual ip addresses. Every time we visit a website, we have to query the server ip of the website through all levels of DNS servers before we can access the server.

DNS-related optimizations generally involve two things: browser DNS caching and DNS preparsing.

1. DNS cache

A picture is worth a thousand words:

The browser will first check the browser cache (browser cache has size and time limit). If the time is too long, the IP address may change and the correct IP address cannot be resolved. If it is too short, the browser will repeatedly resolve the domain name, usually for a few minutes.

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

If the domain name has not been found, the domain name will be sent to the domain name server in the region (usually provided by Internet providers, telecom, Unicom, etc.), and can generally be found on the domain name server in the region.

Of course, it is also possible that the local domain name server is not found, so the local domain name server begins to search recursively.

Generally speaking, it takes 20-120ms for browsers to parse DNS, so there is little optimization for DNS parsing. However, there is such a scenario where there are many images on the website under different domain names. If you resolve the domain names that may be used in advance on the login page, so that the resolution results are cached, this shortens the DNS parsing time and improves the access speed of the website as a whole. This is called DNS pre-resolution.

2. DNS pre-parsing

Let's take a look at MDN's definition of DNS preparsing:

The X-DNS-Prefetch-Control header controls the DNS pre-read function of the browser. DNS pre-reading is a function that enables browsers to actively perform domain name resolution, including all the links to the document, whether it is a picture, CSS, or URL that other users can click on, such as JavaScript.

Because pre-reading is performed in the background, the DNS is likely to be parsed before the corresponding link appears. This can reduce the delay when users click on the link.

Here's a brief look at how to do DNS pre-parsing:

Add it to the page header so that the browser pre-parses the entire page

Manually add the domain name to be resolved through the link tag, such as:

At this point, the study on "how to understand the front-end performance optimization CRP" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report