Front-end page performance optimization indicators

Front-end page performance optimization indicators

1. What indicators are there?

Optimizing the quality of user experience has always been the key to the long-term success of every Web site. The core performance indicators of web pages should continue to evolve over time. The core Web health indicators currently announced by Google Chrome - Core Web Vitals Including loading experience, interactivity and visual stability of page content;
1. Largest Contentful Paint (LCP) : The loading speed of the main content of the Web page, measuring the loading experience: In order to provide a good user experience, LCP should be loaded after the page first starts loading Occurs within 2.5 seconds.
2. First Input Delay (FID) : Measures interactivity. In order to provide a good user experience, the FID of the page should be less than 100 milliseconds.
3. Cumulative Layout Shift (CLS) : Measures visual stability. In order to provide a good user experience, the CLS of the page should be kept less than 0.1.
4. Interaction to Next Paint (INP) , used to measure the overall responsiveness to user interaction on the page

Insert image description here
The above table is the evaluation criteria for various indicators, where the expected coverage refers to at least the corresponding percentage of user tests that can meet the GOOD standard.

LCP(Largest Contentful Paint)

Largest Contentful Paint (LCP) is a metric used to measure the render time of the largest content element visible within the standard report viewport. In order to provide a good user experience, websites should strive for maximum content rendering within the first 2.5 seconds of starting to load the page .
Insert image description here

FID( First Input Delay)

FID (First Input Delay) records the time it takes for the user to interact with the page for the first time. The FID indicator affects the user's first impression of the interactivity and responsiveness of the page. In order to provide a good user experience, the site should strive to make the first input delay less than 100 milliseconds.
Insert image description here

CLS(Cumulative Layout Shift)

In layman’s terms, it’s called visual stability .

Insert image description here
Have you ever experienced the following situation when visiting a web page? The text suddenly moved while reading the article, you suddenly couldn't find where you were reading, or when you clicked the button, the button was moved to another place, causing you to click on something else?
Unexpected movement of page content often occurs due to asynchronous loading of resources or dynamic addition of DOM elements to the page above existing content. The culprit could be an image or video of unknown dimensions, a font that renders larger or smaller than its fallback, or a third-party ad or widget that dynamically resizes itself.
Cumulative Layout Shift CLS helps you solve this problem by measuring how often it happens to real users.
CLS measures the sum of all individual layout change scores for each unexpected style move that occurs throughout the page's lifetime. Movement of the layout may occur any time a visible element changes position from one frame to the next. In order to provide a good user experience, websites should strive to have a CLS score less than 0.1 .
Insert image description here

INP(Interaction to Next Paint)

A standard newly introduced by Google in 2022, INP measures the time it takes for a web page to respond to user interaction, from the moment the user starts interacting to the moment the next frame is drawn on the screen. An
INP of less than or equal to 200 milliseconds indicates good responsiveness.
INP may eventually replace First Input Delay ( FID ) as one of the Core Web Vitals .
Since INP also includes processing time and presentation latency, it has a higher value than first input latency. It also looks at the slowest page interaction, unlike FID which only looks at the first
Insert image description here

Other indicators

FP - First Paint - First rendering, which means that the DOM structure begins to be progressively parsed and reflected on the page.
FCP - First Contentful Paint - First content rendering. At this time, the page already contains some text, icons, etc.
DCL - DOMContentLoaded - DOM Full loading and parsing events trigger
FMP - First Meaningful Paint - the first effective rendering, at this time the page already contains more text, icons, etc.
LCP - Large Content Paint - the revolution is about to win
L - Load page loading is completed
...

2. How to measure and calculate these indicators?

Insert image description here

1. Use Chrome plug-in –web-vitals-extension to get these indicators

1) First download the plug-in and unzip it into a folder
https://github.com/GoogleChrome/web-vitals-extension
Insert image description here
(2) Import the plug-in into Chrome browser
Insert image description here
Insert image description here
(3) Open any page, click the plug-in icon, wait a few seconds, You can see the indicator calculation results
Insert image description here

2、Chrome DevTools

(1) The Performance Insights tab also displays the main Core Web Vitals indicators
Insert image description here
(2) The Performance tab can display other types of indicators:

Insert image description here
(3) Lighthouse will calculate the core indicators LCP and CLS, and evaluate the overall performance of the website. For example: in Google Chrome debugging mode (F12), switch to the Lighthouse tab
Insert image description here
Insert image description here

3、Performance Timeline API

The Performance Timeline API is an extension of the Performance API and can be understood in a narrow sense as the following three main methods in the browser performance object: 1. getEntries()
2. getEntriesByType()
3. getEntriesByName()

4. Example calculation

Insert image description here
Insert image description here

3. How to optimize the page

1. LCP (Largest Contentful Paint) optimization

What are the main elements to consider when optimizing LCP?
1. <img>Elements
2. Elements <image>within elements 3. Elements 4. Elements that load background images through the **url()** function 5. Blocks that contain text nodes or other children of inline text elements level element. The most common reasons for poor LCP are: 1. Slow server response time 2. Javascript and CSS that blocks rendering 3. Slow resource loading time 4. Client rendering<svg>
<video>






How to improve LCP?

Optimize server

Cache HTML offline pages, cache page resources, and reduce browser requests for resources – try not to request useless resources.
Minimize resource blocking rendering: CSS and JavaScript compression, merging, etc.
Optimize images: convert the image format to JPG or WEBP , etc., reduce the size of the image; add fetchpriority="high"attributes to the most important image elements:

<img src="./flower.jpg" class="img-style" id="firstImg"fetchpriority="high">

This will tell the browser to make this request before loading lower priority resources. By default, image requests have a lower priority, and after the page is rendered, the priority of the above-the-fold image increases. Adding fetchpriority=highmeans that the browser can initiate image requests immediately.
1. Rewrite HTML , compress spaces, remove comments, etc. Reduce HTML size and speed up.
2. Use CDN to speed up requests.
3. Use preconnect to establish a link with the server as quickly as possible, and use dns-prefetch to perform DNS (resolve the domain name into the corresponding IP address) search as quickly as possible.
preconnect : The keyword preconnect of the element attribute is a hint to the browser that the user may need a resource from the target resource, so the browser can improve the user experience by preemptively initiating a connection to that resource.

<link rel="preconnect" href="//the-domain-to-be-preconnect.com"crossorigin="anonymous" />

dns-prefetch :
Chrome and Firefox 3.5+ have built-in DNS Prefetching technology and have made corresponding optimization settings for DNS pre-resolution. So even if this attribute is not set, Chrome and Firefox 3.5+ can automatically pre-parse in the background. At present, many large sites have also applied this optimization, such as Taobao:
Insert image description here

Optimize resources that block rendering

Both JavaScript and CSS are resources that will block page rendering. It is necessary to compress CSS and JavaScript files as much as possible, delay loading of JavaScript that is not used on the first screen , and inline key CSS to reduce blocking time.

Optimize resource loading time

Optimize images. Convert the image format to JPG or WEBP, etc., and reduce the size of the image. Preload important resources, such as adding rel="preload"attributes to the style tag and using Gzip and Brotli to compress page resources to reduce transmission time.

Example

1) Transcode large images

Display the image directly on the page: the image size is 8,651.1 KiB, about 8 megabytes
Insert image description here

Insert image description here
Convert the image to base64 encoding before displaying it
Insert image description here
Insert image description here
Insert image description here

(2) Use preconnect to preload

Insert image description here
Calculation results:
Insert image description here

2. FID (First Input Delay) optimization

What elements does FID consider?

When the browser receives user input, the main thread is busy executing a relatively long task. Only when this task is completed can the browser respond to the user's input. The amount of time it must wait for the user's FID value on this page .
For example, all of the following HTML elements need to wait for ongoing tasks on the main thread to complete before responding to user interaction:
1. Text input boxes, checkboxes, and radio buttons ( <input>,<textarea>)
2. Selection drop-down menus ( <select>)
3. Links ( <a>)

How to improve FID

The following aspects are important indicators for improving FID , which are the same as the methods for improving LCP above :
shrink and compress JavaScript files
, delay loading of JavaScript
that is not needed on the first screen , and minimize unused polyfills (polyfill: used to implement native features that are not supported by browsers). API code)

3、CLS(Cumulative Layout Shift)优化

Don't use sizeless elements

Elements such as images and videos always need to include width and height size attributes. Modern browsers will set the default aspect ratio of the image based on the width and height attributes of the image. Once the aspect ratio is known, the browser can calculate and reserve enough for the element. space.
Never insert content on top of existing content unless in response to user interaction. This ensures expected layout changes.

Reserve advertising space in advance

Many page advertisements are dynamically inserted, so be sure to reserve a certain amount of space for advertising slots in advance.

Be wary of font changes

Fonts are usually large files and take a while to load. Some browsers do not render text until the font is downloaded. font-display: swapTell the browser to use the system font for rendering by default, and then replace the custom font after the download is complete. Alternatively, you can use <link rel="preload">more Load font files early.
Insert image description here

4. INP (Interaction to Next Paint) optimization

What are the main factors considered by INP?

Any mouse click on an interactive element.
Click on interactive elements on any device, including touch screens.
Press a key on the physical keyboard or on-screen keyboard.

How to improve and optimize INP

The best way is to optimize the main thread work

Use as few plugins as possible

This means making sure you keep things like third-party fonts to a minimum (i.e., only use system fonts) and that you don't use too many plugins while the page loads.

For example, let’s say you have a WordPress site with 15 ad plugins specifically designed to display ads on your pages – maybe you don’t have to use them all.

Turning off 90% of plugins will help increase INP and simplify main thread work - as this delays page loading.

Reduce the number of http requests

80% of response time is spent downloading web content (images, stylesheets, javascripts, scripts, flash, etc.). Reducing the number of requests is the key to shortening the response time. CSS Sprites : It is to combine multiple images into one image, and then use CSS to control where and where the entire image is displayed, which can reduce the number of requests for images. quantity

#home {  
	width: 46px; 
	height: 44px;  
 	background: url(img_navsprites.gif) 0 0;
 }

Inline images : Embed images into web page text via encoded strings. For example, the inline image below displays a checked checkbox.

.sample-inline-png {   
	 padding-left: 20px;    
	 background: white url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD///+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4Ug9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC') no-repeat scroll left top;
 }

5. Other types of improvements

HTML class

(1) Reduce the number of DOM elements

Too many elements in a web page impose a heavy burden on the loading of the web page and the execution of scripts. There will be a big difference in loading speed between 500 elements and 5,000 elements.
Want to know how many elements are in your web page? You can calculate it with a simple command in your browser.

document.getElementsByTagName('*').length

(2) Reduce the number of iframes

When using iframes, you should pay attention to understanding the advantages and disadvantages of iframes:
Advantages
1. It can be used to load slower content, such as advertisements.
2. Security sandbox protection. The browser will perform security control on the content in the iframe.
3. The script can be downloaded in parallel
Disadvantages
1. Even if the iframe content is empty, it consumes loading time
2. It will prevent the page from loading
3. No semantics

(3) Avoid 404

We are all familiar with 404 , which means that the server did not find the resource. We must pay special attention to the 404 situation and not on the web resources we provide. The client sends a request but the server returns a useless result, and time is wasted.

What's worse is that our web page needs to load an external script, and a 404 is returned . Not only does it block the downloading of other scripts, but the downloaded content (404) will also be parsed by the client as Javascript .

(4) Avoid empty image src

**straight HTML**
<img src="">

JavaScript**var img = new Image();
img.src = "";

(5) Others

CSS classes

(1) Pin the style sheet to the top

Placing the style sheet ( css ) in the HEAD of the web page will make the web page appear to load faster, because doing so allows the browser to gradually load the downloaded web page content. This is especially important for web pages with a lot of content. Users do not have to wait on a white screen, but can watch the downloaded content first.

If you place the style sheet at the bottom, the browser will refuse to render the downloaded web page, because most browsers strive to avoid redrawing when implementing it. The content in the style sheet is the key information for drawing the web page. You have to apologize until it is downloaded. Audience

(2) Avoid css expressions

CSS expressions can dynamically set CSS properties and are supported in IE5-IE8. Expressions will be ignored in other browsers . For example, the following expression sets different background colors at different times.

background-color: expression( (new Date()).getHours()%2 ? "#B8D4FF" : "#F08A00");

The problem with CSS expressions is that they are recalculated far more times than we think, not only when the web page is drawn or resized, but even when we scroll the screen or move the mouse, so we try to avoid using it. To prevent performance loss caused by improper use.

If we want to achieve similar effects, we can do it through a simple js script.

<html>
	<head></head>
	<body>
		<script type="text/javascript">
			var currentTime = new Date().getHours();
			if (currentTime%2) {    
				if (document.body) {        
					document.body.style.background = "#B8D4FF";    
					}
				}else {    
					if (document.body) {        
						document.body.style.background = "#F08A00";    
						}
					}
			</script>
		</body>
</html>

(3) Replace @import with

The reason to avoid using @import is simply that it is equivalent to placing the css at the bottom of the web page content.

(4) Resource compression

Use modular tools such as webpack , gulp/grunt , and rollup to compress the CSS code to make the file smaller and greatly reduce the browser's loading time.

(5) Reasonable use of selectors

The css matching rules are from right to left. For example, **#markdown .content h3** matching rules are as follows:
1. First find the h3 tag element
2. Then remove elements whose ancestors are not .content
3. Finally remove elements whose ancestors are not # markdown elements

If there are more nesting levels and there are more elements on the page, the time cost of matching will naturally be higher.
So when we write a selector, we can follow the following rules:

1. Do not nest too many complex selectors, preferably no more than three levels.
2. Use id selectors to avoid nesting.
3. Wildcards and attribute selectors are the least efficient, avoid using them.

Summarize:

The way to achieve performance in css can be considered from three aspects: selector nesting, attribute characteristics, and reducing http requests. At the same time, we should also pay attention to the loading order of css code.

JS class

(1) Put the script to the bottom

1. Put the script at the bottom, so that the content required for web page rendering can be loaded and displayed to the user as quickly as possible.
2. Now mainstream browsers support the defer keyword, which allows you to specify a script to be executed after the document is loaded.
3. The async keyword is newly added in HTML5, which allows scripts to be executed asynchronously.

(2) Using external Javascirpt and CSS files

1. Using external Javascript and CSS files allows these files to be cached by the browser, thereby reusing content between different requests, and also reducing the size of web page content.
2. The deciding factor in using external Javascript and CSS files is the reuse rate of these external files. If users will visit the same page multiple times when browsing our pages or different pages where the script can be reused, then the external file form can bring you Great benefit. But for pages that users usually only visit once, such as the homepage of microsoft.com, inline javascript and css can provide relatively higher efficiency.

(3) Streamline Javascript and CSS

Remove all spaces and comments from Javascript or CSS? Personally, I don’t think it makes sense. The code has no format.

body {   
	 line-height: 1;
 }
 ol,  ul {   
 	 list-style: none;
 }
 blockquote, q {   
 	 quotes: none;
 }

Condensed version

body{line-height:1}ol,ul{list-style:none}blockquote,q{quotes:none}

Statistics show that the streamlined file size is reduced by 21% on average , and even when Gzip is applied, the file size will be reduced by 5%.

(4) Remove duplicate scripts

Duplicate scripts not only waste browser download time, but also waste parsing and execution time. The general approach to avoid the introduction of duplicate scripts is to use a unified script management module, which not only avoids the introduction of duplicate scripts, but also takes into account script dependency management and version management.

(5) Reduce DOM access

Accessing DOM elements through Javascript is not as fast as we imagined. Web pages with many elements are especially slow. We should pay attention to Javascript's access to DOM.

1. Cache elements that have been accessed
2. Avoid fixing layout through Javascript

Optimization summary

Mainly divided into loading performance optimization and rendering performance optimization

Loading performance optimization

1. Reduce the number of requests;
2. Reduce the size of requested resources;
3. Network optimization;

(1) Reduce the number of requests

Why reduce the number of requests?
Take chrome as an example:
under the same domain name, the number of concurrency for the same GET request is 1, which means that the next request will not be executed until the previous request is completed, otherwise it will be placed in the queue waiting to be sent;
under the same domain name, the number of concurrent GET/POST requests will be 1. The number of concurrencies is 6.
Therefore, too many resource requests are definitely more time-consuming than too few requests, which directly affects the loading speed of web pages;

Ways to reduce the number of requests
(1) Image resource
CSS sprite image technology combines some commonly used and reused small images into one large image. When used, it is positioned on a specific small image through background-position (background-position);
font Icon An icon font is smaller than a series of images. Once the icon font is loaded, the icon will be rendered immediately without downloading an image, which can reduce HTTP requests.
base64 encoding
(2) Proper use of cache
(3) Merge CSS and JS files

(2) Reduce the size of requested resources

1. Image compression: transcoding, using font icons, etc.
2. File compression: gzip compression, Tree Shaking technology, etc.

(3) Network optimization

1.CDN
2. Third-party components are loaded on demand

Rendering performance optimization

Browser rendering process

  1. Parse HTML to generate a DOM tree.
  2. Parse CSS to generate CSSOM rule tree.
  3. Parse JS and operate DOM tree and CSSOM rule tree.
  4. Merge the DOM tree and CSSOM rule tree together to generate a rendering tree.
  5. Traverse the rendering tree to start layout and calculate the position and size information of each node.
  6. The browser sends the data of all layers to the GPU, and the GPU synthesizes the layers and displays them on the screen.
    Insert image description here
    Rearrangement
    . When the position or size of a DOM element is changed, it will cause the browser to regenerate the rendering tree. This process is called rearrangement.
    Redrawing
    When the rendering tree is regenerated, each node of the rendering tree must be drawn to the screen. This process is called redrawing. Not all actions will cause a reflow, such as changing the font color, which will only cause a redraw.
    The two operations of reflow and redraw are very expensive, because the JavaScript engine thread and the GUI rendering thread are mutually exclusive, and only one of them can work at the same time, so reflow and redraw will block the main thread.

Rendering performance optimization methods

(1) Resource loading priority control

1. The css introduction is placed at the end of the head tag, and the script script is placed at the end of the body tag;
2. The dependency between the script and DOM /other scripts is very strong: defer<script> to the setting 3. The dependence between the script and DOM /other scripts is not strong: yes Set async 4. Preload loads necessary resources for the current route, with high priority. Generally, preload is used for Bundle resources (static resource file packages, excluding executable files); 5. Refetch has low priority, loading resources when the browser is idle. Generally used to load non-homepage resources; 6. preload/prefetch preload/prefetch can control the priority of HTTP requests, so as to achieve faster response to key requests; dns-prefetch can pre-resolve the DNS of the host address.
<script>


(2) Reduce reordering and redrawing

1. Reduce page DOM operations;
2. Perform a series of operations on DOM elements to remove the DOM element from the document flow. After the modification is completed, bring it back to the document. For example: hide elements ( display:none);
3. When modifying styles with JavaScript , it is best not to directly modify a single style attribute, but to replace the class to change the style;
4. Use anti-shake and throttling reasonably;

(3) Use cache

Page cache ( keep-alive), interface cache (reduce page refresh caused by data update)

Guess you like

Origin blog.csdn.net/A__men/article/details/129146018