background

Recently, I met an optimization requirement of the product. The product said that the first loading time of the page was too long, about 4-5 seconds, and asked if there was a good solution. Could you optimize it and produce a solution in one second?The above joke, without further discussion, the first page loading time is too long is a version of the project will encounter the problem, next I will optimize the process and ideas to share.

Troubleshoot problems

View the splitChunck of the project webpack

It is true that the dist package is loaded on demand, but the dist package is still very large after packaging. Now to troubleshoot the problem of the package, we need to use webPackd’s build package analysis plug-in webpack-bundle-Analyzer.

webpack-bundle-analyzer

Webpack-bundle-analyzer generates visual pages based on build statistics that help you analyze the size of the modules contained in your package, helping to improve code quality and site performance.

Webpack – bundle – analyzer principle

The essence of what this plugin does is analyze the stats parameter passed in compiler.plugin(‘done’, function(stats)). Stats is a statistics class from WebPack that calls the toJson() method on the Stats instance to get formatting information. ToJson method support parameter source.

How to output stats.json

When starting Webpack, two parameters are supported:

  • –profile: Records the time consuming information during the build process;
  • — JSON: Outputs the build results in JSON format, culminating in a.json file that contains all build-related information.
Start Webpack with these two parameters and run Webpack --profile --json > stats.json. You will see an additional stats.json file in your project. This stats.json file is intended for use by visual analysis tools.Copy the code

As shown in the figure, webPack generates stats.json files that contain chunks, which are chunks of the webpack. You can see dependencies, file sizes, and so on. The plugin then gets chunks from stats.json and eventually draws the map using Canvas. The code is located inanalyzer.jsThe getViewerData method in.

Method of use

Visually display the building blocks

  • What is contained in the packaged files;
  • The proportion of the size of each file in the total, to see which files are large at a glance;
  • Inclusion relationships between modules;
  • The Gzip size of each file.

Optimization idea

In normal project development, we often introduce various third-party modules in order to speed up development. However, sometimes these modules contain a lot of modules that we don’t need, and are packed in at the same time. This makes the build package “bloated”, so we have to kill the modules that we don’t need.

By building modules that can be seen hightlight, js, html2canvas. Js, JSPDF. Min. These three third-party libraries of js is large, to look for in the code found this belongs to introduce as without using NPM package, decisive kill, repackaging, build before optimization package volume of 3.59 M, After optimization, the package volume is 2.42m, which is more than 1M smaller.

UE

When the home page is loaded too long, the most intuitive feeling is that global loading is too long. All request data is loaded with global loading. At this time, it is necessary to consider using local loading instead of global loading.

Global and local loading are compared

Example of global transition loading

Partial transition lodaing example

contrast Global transition loading Partial loading
advantages 1. Restrict user actions (no other actions can be triggered during a request pending process); 2. Unified display of data after comprehensive rendering. 1. Data will be displayed immediately upon return, providing good interactive experience; 2. If the interface is unstable, some parts of our page can be displayed normally
disadvantages 1. If the number of current page requests is too large or the interface speed is too slow, users may wait for a long time. 2. If an interface error occurs, the user experience is poor User action behavior cannot be restricted
### local loading mode
The mode of partial transition loading can be divided into small loading, placeholder map, skeleton screen, etc
# # # # small loading
Generally, the data of chart class is loaded in the way of partial transition and small loading. For example, Ant Desigh’s table loads data remotely.
# # # # placeholder figure
Generally, image data loading will use the way of placeholder map, the main reason is to avoid backflow, so that the overall layout of the document will not change after the rendering process after the completion of image loading, and the performance is optimized, such as Baidu picture module.
# # # # frame screen
General articles or other display situations will use the skeleton screen, such as digging gold using skeleton screen transition loading data;

network

Check the request duration of the interface

TimeIt can be seen from above that the interface length is about 130ms-350ms, which is relatively normal, but through observationWaterfallAttribute discovery interfaces have long time intervals between them. Why are concurrent requests asynchronous and not started at the same time? At this point we need to know the maximum number of concurrent links in the major browsers.

Maximum number of concurrent links of the browser

Some major browsers generally limit the number of concurrent connections to the same server. Due to the number of ports and thread switching overhead, it is not possible to have an unlimited number of concurrent requests, hence the concurrency limit and HTTP/1.1 Keep Alive.

Therefore, IE6/7 has only 2 concurrency under HTTP/1.1, but HTTP/1.0 has 4. With the development of technology, load balancing and a large number of applications of all kinds of NoSQL are basically enough to deal with the problem of C10K. But not every site knows how to use domain hash, or multiple domain names, to speed up access.

As a result, the new browser increases the concurrency limit, but still keeps it under eight.

The table below shows the maximum number of concurrent connections between HTTP 1.1 and HTTP 1.0 in some major browsers:

The browser HTTP / 1.1 HTTP / 1.1
Chrome 4+ 6 6
Safari 3, 4 4 4
firefox 6 6
Opera 10.51 + 8 8
IE 10 11 6 6
IE 9 10 10
IE 8 6 6
IE 6 7 2 4
### View the problem in terms of request concurrency
After understanding the maximum number of concurrent links in the browser, we found that the page 11 requests under Google Browser are not divided into two concurrent links, but divided into five concurrent links, but the specific reason is not analyzed, this time is the need to use Chrome debugging – performance analysis toolperformanceAnalyze.

performance

The Performance panel records and analyzes all the activity of the page at run time.

The overview area

Here is the sequence of events executed in each time period during the overall interface rendering. From the above figure, we can know what we have done in each time period. When the mouse is put up, we can also view the rendering of the interface in each time period in the form of a large picture. Performance presents several key metrics in chronological charts.

  • FPS, the number of frames per second, is used to measure the performance of page animation. The higher the green bar in the FPS chart, the better the experience. If a long red bar appears, it indicates that a long frame appears at the time end, which may affect user experience. (Most current devices have a screen refresh rate of 60 times per second)
  • CPU, indicating CPU usage, has the same color meaning as in the Summary module below. The crossing times of the color blocks in the row can be used to analyze which types of events take longer to find performance bottlenecks
  • NET, each color bar indicates the loading of a file. Blue for HTML files, yellow for JS files, purple for style files, green for media files, and gray for other resources
  • Screenshots, a snapshot of the page at any given moment
  • V8 memory usage (HEAP memory HEAP), etc

Performance panel (network request and main thread various events)

The performance panel consists of the following parts

  1. Network Here, we can intuitively see the sequence and duration of resource loading
  2. Interactions are used to record user Interactions, such as mouse clicks, text input, animations, and so on
  3. Timings are used to record the data information such as FP, FCP and LCP generated at some key time nodes
  4. Main is an important part of the Performance tool. It records the execution records of the Main thread in the rendering process. Click Main to see the details of a task execution
  5. Compositor Execution record of the Compositor thread, which records layer compositing operations after the HTML Paint phase
  6. Raster Raster thread pool, used to make gpus perform rasterized tasks
  7. GPU This is a record of the execution of the main thread of the GPU process. For example, you can view the time when GPU acceleration is enabled.

Statistical summary area

Statistics of performance indicators within the time range of performance testing:

Summary Statistics chart

  • Loading: Loading time
  • Scripting: JS calculates time
  • Rendering time: Rendering time
  • Painting: Painting time
  • Other: Other time
  • Idle: indicates the Idle time of the browser

Bottom-up event duration sequencing

Call Tree event Call ordering

Event Log Indicates the sequence in which events occur

The performance practice

The following is a practical example of performance in this project optimization process to deepen the understanding and use of relevant parameters of performance.

Focus on the performance panel Network

From the figure above, we can see two obvious messages:

  1. There are several low-priority requests in front, blocking the resource interface with higher priority requests.
  2. There are many images on the page, and the number of images that can be loaded at the same time is limited.

In both cases, high-priority resource acquisition (resources that control page rendering) is blocked in the business.

window.requestIdleCallback

Low priority requests browser free, does not affect the process of the main thread . Here we use the window requestIdleCallback method, put the request of the low priority in the callback function, to call the function in the browser’s free time line. This enables developers to perform background low-priority work after the main event loop.

Window. RequestIdleCallback has two parameters, one is a callback, the event loop free time to be called function reference, one is the options, there is only one timeout parameter, if you specify the timeout and have a positive, And if the callback has not been invoked by timeout milliseconds, it will be enforced in the next idle period. After modification, about 300ms loading time was saved through Performance monitoring.

Sprite/Sprite

Unified Sprite image processing is carried out for the background images on the page. After combining multiple images into one image, all the resources required can be downloaded with only one network request, reducing the consumption and resource waste of establishing connections.

Fire chart &Summary statistics chart

View the regional flame chart and statistical reports. JavaScript scripts consume a large amount of CPU performance, indicating that too much logic is executed in JS. You can optimize JS to improve performance.

Results contrast

Optimization before loading a long article content for the first time to load 5-6s;After optimization, the first loading only takes about 1.5 seconds;

conclusion

Through Performance, you can not only understand project performance and optimization direction, but also intuitively understand the browser rendering principle and workflow, and connect front-end concepts such as browser system architecture, message loop mechanism, and rendering pipeline. This optimization also recognizes the importance of ESlint in team development, limiting the use of unused NPM packages by developers, and preventing unnecessary NPM packages from entering the project at its root. And the background image Sprite figure processing, low priority tasks put window. RequestIdleCallback processing, etc., in some good development specification is also very important, can improve the quality of finished product of the project.

portal

Talk to you about how to optimize the front-end performance

A partial transition to improve user experience

Introduction to webPack Automation Architecture