Front-end performance optimization is an essential ability for every front-end development engineer, whether in interviews or in the actual development process. This article summarizes my understanding of front-end performance optimization in my years of development experience, and I hope it will be helpful to you. Because there are many optimization directions involved, I will not explain some details in detail. If you are interested, you can learn more about it. I won't say much. , the text begins.
importance
The performance of a good front-end project is very important, especially for ToC users. A good user experience can greatly improve the business conversion rate, so the quality of the performance is related to the business revenue. For a commercial company, as long as it is related to money, it is extremely sensitive and important.
measure
In 2020, Google proposed a new generation of Web performance experience indicators Core Web Vitals, including LCP, FID, CLS three indicators.
- Largest Contentful Paint (LCP): Measuring Loading Experience: To provide a good user experience, LCP should happen within 2.5 seconds of the page first starting to load.
- First Input Delay (FID): To measure interactivity, in order to provide a good user experience, the FID of the page should be less than 100ms.
- Cumulative Layout Shift (CLS): A measure of visual stability, in order to provide a good user experience, the CLS of a page should remain less than 0.1.
For these indicators, it can be directly obtained through Lighthouse in the browser development tool whether the standards are met. The conclusions drawn in this way are quick and intuitive, have no intrusion on the original website, and do not affect the performance of real users. However, it also has shortcomings. It does not support complex business logic scenarios, and the amount of monitored data is too small to restore the usage of most real users.
Therefore, in order to obtain real and comprehensive data, most companies will develop a monitoring plan or use a third-party monitoring platform, which will have a certain performance impact on the website, but it can be optimized through more comprehensive performance data analysis. .
Performance optimization direction
Based on the above three experience indicators, we can optimize from the life cycle of page loading, preprocessing before page loading, loading process, page rendering, user interface interaction and other stages. The following will optimize for different stages. , you can choose and optimize according to the situation of your own project.
Preprocessing before loading
- Use dns-prefetch and preconnect to reduce DNS resolution, establish TCP connection and perform TLS handshake time, dns-prefetch: Tell the browser to perform DNS resolution on the specified domain name. When the domain name resource is subsequently requested, the DNS resolution time can be saved. preconnect: Tell the browser to establish a connection with the server at the specified domain name. When the domain name resource is subsequently requested, the established connection can be used directly, saving the time of DNS+TCP+TLS
<link rel="dns-prefetch" href="https://s1.static.com">
<link rel="preconnect" href="https://s1.static.com">
- Use preload/prefetch to let the browser load the required resources in advance. Preload can indicate which resources are needed immediately after the page is loaded. The browser preloads the resources before the main rendering mechanism intervenes. This mechanism allows the resources to be loaded earlier. It is loaded and available, and it is less likely to block the initial rendering of the page, thereby improving performance; prefetch uses browser idle time to download or prefetch documents that users may access in the near future. Remember not to mix preload and prefetch, they are suitable for different scenarios. For example, using preload and prefetch for the same resource will cause unnecessary secondary downloads.
<link href="xx.js" rel="prefetch">
<!--as表示指定资源类型-->
<link href="xx.js" rel="preload" as="script">
during loading
1. Reduce the size of resources as much as possible
- The business code itself should not be repeated as much as possible, improve the use of components, and prompt the reuse rate of the code. Here is not only JS, but also CSS styles.
- Compress static resources, generally scaffolding will be processed by default, self-built projects can check whether there is compression
- The DOM level control in html should not be too deep and unnecessary DOM usage should be reduced, and the use of pseudo-elements and CSS should be used as much as possible
- Check whether the dependencies of the project are repeatedly referenced. Different dependencies may refer to the same version of the package, which can be viewed through the webpack-bundle-analyzer plug-in analysis.
- UI component libraries or other libraries are loaded on demand using the babel-plugin-import plugin
- Components are loaded on demand, using AsyncComponent to only load above-the-fold components
- Dynamically import large third-party modules, import('/modules/echart.js) .then((module) => {}), but don't abuse it, use it in combination with actual scenarios
- Reduce the size of 3rd party libraries like Moment.js/lodash, etc., use lightweight alternatives or re-implement it yourself
- For those who have higher requirements for the second opening of the first review, the interface of the first screen request can be split, and the fields that need to be used on the first screen can be quickly responded, and other data are loaded asynchronously.
- Using tree shaking, when we introduce other modules into the project, it will automatically shake out the code that we don't use, or the code that will never be executed, detect it in the Uglify stage, and not package it into the bundle
- The simplification of HTTP header cookies, the removal of unnecessary cookies, and the deployment of independent domain names for static resources to avoid requests carrying cookies
- The HTTP header enables gzip compression, which can greatly reduce the amount of data transmitted over the network
- HTTP headers enable keep-alive
- Upgrading HTTP to 2.0, 2.0 header compression reduces the amount of data transmission, can save the network traffic occupied by message headers, and has the advantages of multiplexing and other advantages
2. Reduce the number of resources as much as possible
- The number of JS/CSS should not be too scattered. To avoid making too many requests, it is necessary to combine some resources together to reduce the number of requests. However, in the process of merging, there is a trade-off between volume and quantity. The less the better, the maximum volume can be controlled within a range for merging.
- Some small-scale JS/CSS can be inlined into HTML to reduce the number of requests
- To reduce the initiation of preflight request OPTIONS, you can set the Access-Control-Max-Age field through the server or initiate a simple request instead
- Cancel invalid requests, form submissions are frequently clicked, and there are still unfinished requests when routing is switched. These will generate invalid requests, which are bad for the server and user experience
caching strategy
- Enable http strong caching and negotiation caching, and use different caching strategies for different types of resources
- Enable CDN service for static resources
- For data that does not change frequently, including external JS/CSS resources, front-end browser caching can be performed to reduce requests, but such caches need to be cleared and updated.
3. Other resource optimization
- Image webp use, for supported devices use webp
- Crop the picture, and crop it according to the usage scene
- Do not package the large image in the project, upload it to a separate static resource server or CDN
- Compress the image before uploading, remember not to use the original image
- Set the size of the image label to prevent the page layout from shaking during image loading and affect the value of the CLS indicator
- Lazy loading of images beyond the screen
- Use the iconfont font scheme for a large number of small icons in the project
- Generate on-demand text whenever possible when using third-party font libraries
- When loading fonts, the page text will flicker and shake to a certain extent. You can use preload to load it in advance before entering the page you need to use.
When the page is rendered
- Turn on the skeleton screen to improve the user experience and avoid the white screen stage when loading into the rendering process
- For scrolling to large lists use virtual lists
- Use CSS3 animations as often as possible
- Use requestAnimationFrame to monitor frame changes so that rendering occurs at the correct time
- Use CSS reasonably, avoid wildcards, maximize style inheritance, use less tag selectors, reduce deep nesting, etc.
user interface interaction
- Reduce page reflow and redraw
- The use of anti-shake throttling
- Reasonable use of requestAnimationFrame animation instead of setTimeout
- When GPU acceleration is enabled, the following properties (CSS3 transitions, CSS3 3D transforms, Opacity, Canvas, webGL, Video) can be used in CSS to trigger GPU rendering
- Reduce the execution time of JavaScript scripts and put some time-consuming tasks unrelated to DOM manipulation into Web Workers for execution
- Mark the element that needs to be animated at a certain time in the future as will-change, so that the rendering engine will generate a separate layer for the element
at last
This article lists a lot of directions for front-end performance optimization, and there are many others that are not involved, such as small programs, other special optimizations in the Vue/React framework, and optimization of native capabilities of apps. The description of the above optimization directions is relatively simple. Students who are interested in the specific practical operation and principles can do more research. Faced with so many optimization directions, how to choose.
There is no so-called absolute optimization. It is necessary to combine the application scenarios of the current project and the full performance analysis of the project to find the deficiencies in a certain direction, optimize them in a targeted manner, and select an appropriate solution. I hope everyone can find their own suitable optimization direction and optimize the project properly. If you find it useful after reading this article, remember to give a like and support, and you may use it one day if you collect it.
Focus on front-end development, share dry goods related to front-end technology, public account: Nancheng Front-end (ID: nanchengfe)
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。