Summary of recent front-end performance optimization

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 from many years of development experience. I hope it will be helpful to everyone. Because there are many optimization directions involved, some details will not be explained in detail. If you are interested, you can learn more. 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 performance is related to the revenue of the business. For a commercial company, as long as it is related to money, it is extremely sensitive and important.

Measurement

In 2020, Google proposed a new generation of Web performance experience indicators Core Web Vitals, which includes three major indicators: LCP, FID, and CLS.

  • Largest Contentful Paint (LCP): Measuring the loading experience: To provide a good user experience, LCP should occur within 2.5 seconds after the page first starts loading.
  • 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.
  • Cumulative Layout Shift (CLS): A measure of visual stability. In order to provide a good user experience, the CLS of the page should be kept less than 0.1.

For these indicators, you can directly use Lighthouse in the browser development tool to determine whether the standards are met. The conclusions drawn in this way are fast and intuitive, without 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, the amount of monitored data is too small, and it cannot restore the usage of most real users.

Therefore, in order to obtain real and comprehensive data, most companies will develop a monitoring solution or use a third-party monitoring platform. This will have a certain impact on the performance of 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. We will optimize for different stages below. , everyone can choose and optimize according to the situation of their own project.

Preprocessing before loading

  1. Use dns-prefetch and preconnect to reduce DNS resolution, establish TCP connections and perform TLS handshake time. dns-prefetch: tells the browser to perform DNS resolution on the specified domain name. When subsequently requesting the domain name resource, the time of DNS resolution can be saved. preconnect: Tells the browser to establish a connection with the server of the specified domain name. When subsequently requesting the domain name resource, you can directly use the established connection, saving the time of DNS+TCP+TLS.
< link  rel = "dns-prefetch"  href = "https://s1.static.com" > 
< link  rel = "preconnect"  href = "https://s1.static.com" >
  1. Use preload/prefetch to allow the browser to load required resources in advance. Preload can indicate which resources are needed immediately after the page is loaded. The browser preloads before the main rendering mechanism intervenes. This mechanism allows resources to be loaded earlier. get loaded and available, and are less likely to block the initial rendering of the page, thus improving performance; prefetch uses browser idle time to download or prefetch documents that the user 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 at the same time will cause unnecessary secondary downloads.
< link  href = "xx.js"  rel = "prefetch" > 
<!--as indicates the specified resource type--> 
< link  href = "xx.js"  rel = "preload"  as = "script" >

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 code reuse rate. This is not only JS, but also CSS styles.
  • Compressing static resources is generally handled by scaffolding by default. Self-built projects can check whether there is compression.
  • The DOM level control in HTML should not be too deep and unnecessary use of DOM should be reduced. Use pseudo elements and CSS as much as possible.
  • Check whether the dependency packages of the project have repeated references. Different dependency packages may reference the same package of different versions. This can be viewed through the webpack-bundle-analyzer plug-in analysis.
  • UI component libraries or other libraries use the babel-plugin-import plug-in for on-demand loading.
  • Components are loaded on demand, using AsyncComponent to only load first-screen components
  • Dynamically import third-party relatively large modules, import(‘/modules/echart.js) .then((module) => {}), but do not abuse it, use it in combination with actual scenarios
  • Reduce the size of third-party libraries, such as Moment.js/lodash, etc., use lightweight alternatives or re-implement yourself
  • If you have high requirements for instant opening of the first comment, you can split the interface for the first screen request, quickly respond to the fields needed for the first screen, and load other data 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. It will be detected in the Uglify stage and will not be packaged into the bundle.
  • Simplify HTTP header cookies, remove unnecessary cookies, and deploy static resources in independent domain names to avoid requests carrying cookies.
  • Turning on gzip compression in the HTTP header can greatly reduce the amount of data transmitted over the network.
  • HTTP header enable keep-alive
  • Upgrading HTTP to 2.0, 2.0 header compression reduces the amount of data transmission, can save network traffic occupied by message headers, and also has advantages such as multiplexing

2. Reduce the number of resources as much as possible

  • The amount of JS/CSS should not be too scattered to avoid initiating too many requests at once. It is necessary to merge some resources together to reduce the number of requests. However, in the process of merging, there needs to be a trade-off between volume and quantity. Less is not always better. The maximum volume can be controlled within a range for merging.
  • Some small-volume JS/CSS can be inlined into HTML to reduce the number of requests
  • To reduce the number of preflight request OPTIONS, you can set the Access-Control-Max-Age field on the server or initiate a simple request instead.
  • Cancel invalid requests, frequent clicks on form submission, and unfinished requests when routing is switched. These will generate invalid requests, which is bad for the server and user experience.
  • caching strategy
    • Enable http strong caching and negotiated 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 used to reduce requests, but such caches need to be set up with clearing and updating mechanisms.

3. Optimization of other resources

  • Image webp use, for supported devices use webp
  • Image cropping, crop accordingly according to the usage scenario
  • Do not package large images in the project, upload them to a separate static resource server or CDN
  • Compress the image before uploading, remember not to use the original image
  • Set the image label size to prevent the page layout from jittering during image loading and affecting the value of the CLS indicator.
  • Enable lazy loading for images that exceed the screen size
  • For a large number of small icons in the project, the iconfont font scheme can be used
  • When using third-party font libraries, generate on-demand text whenever possible
  • When loading fonts, the text on the page will flicker and jitter. 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 during loading and rendering.
  • For rollover of large lists use virtual lists
  • Use CSS3 animations as much as possible
  • Use requestAnimationFrame to monitor frame changes so that rendering can be performed at the correct time.
  • Use CSS rationally, avoid wildcards, maximize style inheritance, use less tag selectors, reduce excessively deep nesting, etc.

user interface interaction

  • Reduce page rearrangement and redrawing
  • Use of anti-shake throttling
  • Reasonable use of requestAnimationFrame animation instead of setTimeout
  • Turn on GPU acceleration. You can use the following properties in CSS (CSS3 transitions, CSS3 3D transforms, Opacity, Canvas, webGL, Video) to trigger GPU rendering.
  • Reduce JavaScript script execution time and put some time-consuming tasks unrelated to DOM operations into Web Workers.
  • For elements that need to be animated within a certain time in the future, mark them as will-change, so that the rendering engine will generate a separate layer for the element.

at last

This article lists many directions for front-end performance optimization. In addition, there are many other aspects that are not covered, such as other special optimizations in mini programs, the Vue/React framework, and the optimization of native app capabilities. The above description of optimization directions is relatively concise. Students who are interested in specific practical operations and principles can study more. Faced with so many directions of optimization, how to choose?

There is no so-called absolute optimization. It is necessary to combine the application scenarios of the current project and the performance analysis of the entire project to find deficiencies in a certain direction, perform targeted optimization, and choose an appropriate solution. I hope everyone can find their own suitable optimization direction and optimize the project properly. If you find this article useful, please give it a thumbs up and save it so you can use it one day~

Focus on front-end development, share front-end related technical information, public account: Nancheng Big Front-end (ID: nanchengfe)

refer to

A new generation of web performance experience indicators

Front-end performance optimization and request optimization