Practice Guide - Front-end Performance Improvement by 270% | JD Cloud Technical Team

1. Background

When we are tired of developing requirements one after another, it is easy to forget to pay attention to the performance of the website. When we reach a certain node, we suddenly find that as more and more codes accumulate, the website becomes slower and slower.

Starting from such a background, this article sets out to optimize the front-end performance of the website, and summarizes a set of development habits, so that we can maintain high performance during daily development, instead of going back to optimize performance again.

Indicator name before optimization Optimized promote
Lighthouse Performance Score 29 81 279%
FCP (First Contentful Paint first content drawing) 0.7s 0.7s
LCP (Largest Contentful Paint maximum content drawing) 6.2s 2.5s 248%
TTI (Time to Interactive interactive time) 10.1s 2.1s 480%
Speed ​​Index 5.6s 1.8 311%
TBT (Total Blocking Time total blocking time) 820ms 120ms 683%

Comparison before and after optimization:

Comparison before and after optimization

2. Before optimization

The next step is to introduce what events we need to do before optimization:

  1. Learn about performance metrics and measurement tools

  2. Analyze where you need to optimize

1. Understand measurement tools and performance indicators

At the beginning, we just felt that the white screen time was longer when the website page was opened, and the performance was relatively poor. So what specific performance indicators need to be paid attention to?

Here I am using Chrome devtools built-in Lighthouse , Lighthouse is an open source automation tool for improving the quality of web applications.

Lighthouse runs web pages under a series of tests, such as different device sizes and different network speeds. It also checks the page for conformance to accessibility guidelines, such as color contrast and ARIA best practices.

Open Chrome devtools Lighthouse to use.

In a relatively short period of time, Lighthouse can give such a report.

This report analyzes pages in 5 areas: Performance, Accessibility, Best Practices, SEO, and PWA. In terms of performance, some common time-consuming statistics will be given.

before optimization

1.1 Performance

Performance scoring statistics, including the following indicators:

1.1.1 FCP

FCP measures the time it takes for the browser to render the first piece of DOM content after the user navigates to the page. Images, non-white elements, and SVG on the page <canvas>are considered DOM content; anything inside an iframe is excluded.

1.1.2 LCP

LCP measures when the largest content element in the viewport is rendered onto the screen. This approximates when the main content of the page will be visible to the user.

It should be noted that the calculation of LCP is a dynamic process. The last picture in the figure below is the largest content drawing element on this page.

lcp

1.1.3 TTI

TTI measures the time it takes for a page to fully interact.

How is TTI calculated? As shown in the figure below, firstly, the time axis is forwardly searched for a quiet window with a duration of at least 5 seconds (quiet window means that there are no long tasks and no more than two network get requests being processed), and then reverse along the time axis Search for the last long task before the quiet window. If no long task is found, the execution will stop at the FCP step. TTI is the end time of the last long task before the quiet window. If no long task is found, it will be the same as the FCP value.

TTI

1.1.4 Speed Index

Speed ​​Index measures how quickly content is visually displayed during page load. Lighthouse first captures the video of the page loading in the browser and calculates the visual progress between frames.

1.1.5 TBT

TBT measures the total time a page is blocked from responding to user input such as mouse clicks, screen taps, or keyboard presses.

The sum is calculated by adding the blocking parts of all long tasks between First Contentful Paint and Time to Interactive. Any task that takes more than 50 milliseconds to execute is a long task.

The amount of time after 50 milliseconds is the blocking portion. For example, if Lighthouse detects a task that is 70 ms long, the blocking portion will be 20 ms.

The total time of the light red area in the figure below is the TBT score of this page.

TBT

1.2 Best Practices

Used to detect the overall code health of the web application, including whether the document type is included, whether the image aspect ratio is correct, and so on.

1.3 SEO

Used to detect how well search engines understand web content.

2. Analyze the areas that need to be optimized

After understanding the key performance indicators, you can measure the performance of the current website.

As seen above, the comprehensive score is very low, and Lighthouse gives suggestions on where to start optimizing.

2.1 Performance

Performance optimization suggestions mainly include the following points:

  • Reduce unused JS;

  • Reasonably use the image format, webp or avif is faster;

  • Lazy loading of images that are not in view;

  • JS compression;

  • The size of the picture should be appropriate;

  • Reduce unused CSS.

Performance Optimization Suggestions

Issues with websites diagnosed by Lighthouse:

  • There are too many resources to load, there are 147 requests, totaling 11mb;

  • With 40 static resources the cache is only 1 hour

  • The scroll event is not marked {passive: true}), resulting in the need to wait for the listener to finish executing before scrolling the page;

  • Image elements do not have an explicit width and height set;

  • There are too many JS files, the workload of the main thread is too large, and the execution time of JS is too long;

existing problems

2.2 Best Practices

In terms of best practice there are the following questions:

  • The resolution of the picture is too low and the clarity is not enough;

  • No CSP policy is set.

best practice questions

2.3 SEO

SEO has the following problems:

  • no meta description;

  • Images do not have alt attributes;

  • robots.txt is invalid.

The problem with SEO

3. Optimize Performance

According to the Lighthouse report above, let’s take a look at the factors that most affect performance in the project, including the following points:

  • The volume is too large, up to 11mb;

  • If the picture is too large, the picture format will also affect it.

1. Volume optimization

1.1 Code Compression

Check if there is still compressed space, or if there are uncompressed tool libraries.

1.2 Code subcontracting

Analyze the package size through the webpack-bundle-analyzer plug-in, and sub-package some large npm packages and runtimeChunk independently to reduce the package size.

1.3 Components are loaded on demand

React.lazy + Suspense encapsulates lazy-loaded components, and route-level components introduce lazy-loaded components.
At the same time, using the skeleton screen as a lazy loading bottom component can make users perceive faster loading.
Preloading routing components when the mouse moves into the navigation bar can speed up page display.

1.4 Tool library loaded on demand

Load tool libraries on demand via import('xx').then(xx) .

1.5 Upload static resources to CDN

There are some static data stored in json files in the project. These files are uploaded to the CDN and changed to fetch to import on demand.

1.6 Delete unnecessary resources

Check the mf and npm resources introduced in the project, and delete the unused ones.

1.7 Avoid duplicate npm package introduction

Discover the atomic component library introduced by the business component library through npm, and the project itself is the atomic component library introduced through mf, compared to the two-pass atomic component library introduced.

At this time, it is necessary to transform the business component library, and also change it to import with the method of mf.

1.8 Avoid esm dependency nesting

Because the on-demand loading of webpack is marked by import and export, if you want a good on-demand loading effect, you need to avoid the problem of dependency nesting.

1.9 Icons are loaded on demand

The exposure method of the atomic component library mf will cause only one icon to be used, and the chunks corresponding to all icons under the component library will be loaded, resulting in waste of resources.

Create a new icon npm package for on-demand import of icons.

1.10 Summary

Through the above optimization methods, the volume is reduced from 11.7mb to 1.1mb, a reduction of 10.6 times.

Before optimization:

before optimization

Optimized:

Optimized

2. Image optimization

1.1 Image lazy loading

Use the image lazy loading strategy for images that are not on the first screen.

1.2 Image size

When using images, set a reasonable size for the image.

1.3 Image format settings

Webp format images are preferred.

4. Optimizing Best Practices

1. Set CSP policy

2. Set a reasonable image resolution

Optimize the image resolution in the project.

5. Optimize SEO

1. Meta description, keywords optimization

Detailed meta description and keywords can speed up SEO.

<meta name="keywords" content="xx" /> <meta name="description" content="xx" />


2. Add alt attribute to the picture

<img src="smiley.gif" alt="Smiley face" />


6. Comparison before and after optimization

Let's look back at the before and after comparison:

Before optimization, the obvious perceived white screen time is long:

before optimization

After optimization, it can also be opened in seconds when the cache is cleared:

Optimized

Overall performance increased by 270%:

Comparison before and after optimization

Seven, performance monitoring

In order to maintain high performance in subsequent iterations, an internal front-end monitoring platform - Candle Dragon is introduced to monitor front-end performance visually.

The first step is to load the cdn plugin:

<script
  defer
  src="https://h5static.m.jd.com/act/jd-jssdk/latest/jd-jssdk.min.js"
></script>


The second step is to initialize the cdn plugin in the entry file:

useEffect(() => {
  // 初始化测速组件,在这里可以打开一些控制的开关,如是否上报接口
  if (IS_PROD) {
    // @ts-ignore
    jmfe.profilerInit({
      flag: xxx, // 这是应用ID,需要先在烛龙申请应用
      autoReport: true,
      autoAddStaticReport: true,
      autoAddApiReport: true,
      autoAddImageReport: false, // 支持所有图片上报,如果图片多,切记关闭,否则存在性能问题
      performanceReportTime: 8000,
      profilingRate: 1,
    })
  }
}, [])


The third step is to view the monitoring data:

On the Zhulong platform, the widget performance score reaches 96 points:

View monitoring data

The fourth step is to add an alarm and monitor in real time

The Zhulong platform supports multi-dimensional alarm services, adding alarms related to performance indicators, discovering problems in time when performance changes, and optimizing performance.

summary

This article introduces in detail the detailed process of a front-end project optimization, from the problem analysis before optimization to the specific optimization measures, and finally achieved a nearly 3-fold improvement in front-end performance. At the same time, the performance indicators are also placed on the monitoring platform to realize the visual monitoring of front-end performance indicators.

I hope it can be helpful to you, thank you for reading~

References

Author: JD Retail Tang Jiao

Source: JD Cloud Developer Community

Ministry of Industry and Information Technology: Do not provide network access services for unregistered apps Go 1.21 officially released Ruan Yifeng released " TypeScript Tutorial" Bram Moolenaar, the father of Vim, passed away due to illness The self-developed kernel Linus personally reviewed the code, hoping to calm down the "infighting" driven by the Bcachefs file system. ByteDance launched a public DNS service . Excellent, committed to the Linux kernel mainline this month
{{o.name}}
{{m.name}}

Guess you like

Origin my.oschina.net/u/4090830/blog/10094331