web performance issues

1. The problem of slow loading speed of the first screen of SPA (Single Page Application)

First Contentful Paint refers to the time from when the browser responds to the URL address input by the user to when the content on the first screen is rendered. At this time, the entire webpage does not necessarily have to be rendered completely, but it needs to display the content required by the current window. First screen loading is arguably the most important part of the user experience.
We can calculate the time of the first screen through DOMContentLoad or performance.timing.

// 方案一:
document.addEventListener('DOMContentLoaded', (event) => {
    
    
    console.log('first contentful painting');
});
// 方案二:
let 白屏时间 = firstPaint - performance.timing.navigationStart;

Reasons for slow loading
In the process of page rendering, the factors that lead to slow loading speed may be as follows:

  • Network delay problem
  • Whether the resource file size is too large
  • Whether the resource has repeatedly sent requests to load
  • When loading the script, the rendering content is blocked

There are many ways to reduce the rendering time of the first screen, which can be divided into two parts in general: resource loading optimization and page rendering optimization

Several common SPA first screen optimization methods

  • Reduce entry file size

Use lazy loading of routes to load routes in the form of functions. The components corresponding to different routes are divided into different code blocks. When the route is requested, the route will be packaged separately, so that the entry file becomes smaller and the loading speed is greatly increased.
component: () => import('./components/header.vue')

  • Static resource local cache

Back-end return: use HTTP cache, set Cache-Control, Last-Modified, Etag and other response headers; use Service Worker offline cache, and
use localStorage reasonably at the front end

  • UI framework loaded on demand

For example: import { Button, Input} from 'element-ui';

  • Compression of image resources

Although the image resource is not in the encoding process, it is the factor that has the greatest impact on the performance of the page. Appropriate compression can be performed on the image resource.
For the icons used on the page, you can use online font icons or sprite images to combine many small icons into the same image to reduce the pressure of http requests.

  • Components are repackaged

Assume that the A.js file is a commonly used library. Now there are multiple routes using the A.js file, which causes repeated downloads.
In the config file of webpack, modify the CommonsChunkPlugin configuration minChunks: 3 to indicate that it will be used 3 times and above packages are extracted and put into public dependency files, avoiding repeated loading of components

  • Enable GZip compression

After unpacking, let's use gzip to compress and install compression-webpack-plugin, run cnmp i compression-webpack-plugin -D, and modify the webpack configuration.
Corresponding configuration should also be done on the server. If the browser that sends the request supports gzip, send it a file in gzip format.

const CompressionPlugin = require('compression-webpack-plugin')
configureWebpack: (config) => {
    
    
        if (process.env.NODE_ENV === 'production') {
    
    
            // 为生产环境修改配置...
            config.mode = 'production'
            return {
    
    
                plugins: [new CompressionPlugin({
    
    
                    test: /\.js$|\.html$|\.css/, //匹配文件名
                    threshold: 10240, //对超过10k的数据进行压缩
                    deleteOriginalAssets: false //是否删除原文件
                })]
            }
        }
  • use SSR

SSR (Server side), that is, server-side rendering, components or pages generate html strings through the server, and then send them to the browser.
Building a server-side rendering from scratch is very complicated. It is recommended to use Nuxt.js to implement server-side rendering for vue applications

white screen problem

White screen time: It refers to the time from when the screen is blank to when the first screen is displayed after the user clicks a link or opens the browser and enters the URL address. The shorter the page rendering time, the shorter the user waits, and the faster the user perceives the page. This can greatly improve the user experience,

White screen process. The process from inputting url to displaying the screen of the page

1. First, enter the url in the address bar of the browser
. 2. The browser first checks the browser cache-system cache-router cache. If there is one in the cache, it will directly display the page content on the screen. If not, an http request is initiated.
3. Before sending an http request, domain name resolution (DNS resolution) is required to obtain the corresponding IP address.
4. The browser initiates a tcp connection to the server, and establishes a tcp three-way handshake with the browser.
5. After the handshake is successful, the browser sends an http request to the server to request a data packet.
6. The server processes the received request and returns the data to the browser.
7. The browser receives the HTTP response
. 8. Reads the content of the page, renders it in the browser, and parses the html source code
. 9. Parses the HTML file and builds a DOM Tree. Parsing CSS, constructing CSSOM Tree (CSS rule tree)
10. Merging DOM Tree and CSSOM Tree, constructing Render tree (rendering tree),

reflow ( rearrangement ): Calculate node information (Layout) according to the Render tree, also known as reflow, when the rendering tree node changes, it affects the geometric properties of the node (such as width, height, inner margin, outer margin, or float, position, display: none; etc.), causing the position of the node to change. At this time, the browser is triggered to reflow (reflow), and the rendering tree needs to be regenerated. For example, JS adds a new style for a p tag node: "display:none;". As a result, the p tag is hidden, and the positions of all nodes after the p tag will change. At this time, the browser needs to regenerate the rendering tree and re-layout.
repaint ( redraw ): Draw the entire page (Painting) according to the calculated information. The rendering tree node changes, but does not affect the spatial position and size of the node in the page. For example, if the background color, font color, etc. of a div label node change, but the width, height, and inner and outer margins of the div label node do not change, this triggers the browser to repaint (repaint).

Every dom change or css geometric property change will cause a browser rearrangement/redrawing process, and if it is a non-geometric property change of css, it will only cause a redrawing process. So rearrangement will definitely cause redrawing, and redrawing will not necessarily cause rearrangement.

After the browser downloads the HTML, it first parses the header code, downloads the style sheet, and then continues to parse the HTML code downwards, builds a DOM tree, and downloads the style sheet at the same time. When the DOM tree is constructed, immediately start to construct the CSSOM tree. Ideally, the download speed of the style sheet is fast enough, and the DOM tree and the CSSOM tree enter a parallel process. When the two trees are constructed, the rendering tree is constructed and then drawn.
Tips: The impact of the browser security parsing strategy on parsing HTML:
When parsing HTML, encountering inline JS code will block the construction of the DOM tree, and the JS code will be executed first; when the CSS style file is not downloaded , the browser will When parsing HTML encounters inline JS code, the browser suspends JS script execution and HTML parsing. Until the download of the CSS file is completed, the construction of the CSSOM tree is completed, and the original parsing is resumed.
JavaScript will block DOM generation, and style files will block the execution of JavaScript. Therefore, in actual projects, you need to focus on JavaScript files and style sheet files. Improper use will affect page performance.

White Screen - Performance Optimization

  • DNS resolution optimization

DNS (Domain Name System) is the English abbreviation of Domain Name System. It is an organization's system management agency that maintains the correspondence between the IP of each host in the system and the host name (domain name).

Optimize DNS resolution for the DNS Lookup link.
1. DNS cache optimization
2. DNS preloading strategy
3. Stable and reliable DNS server

  • TCP network link optimization

  • Server-side processing optimization
    Back-end optimization

  • Browser download, parsing, rendering page optimization
    1) Streamline HTML code and structure as much as possible
    2) Optimize CSS file and structure as much as possible
    3) Be sure to place JS code reasonably, try not to use inline JS code
    4) Inlining the critical CSS needed to render above-the-fold content into the HTML makes the CSS download much faster. It can be rendered after the HTML download is completed, and the page rendering time is advanced, thereby shortening the rendering time of the first screen;
    5) Delaying the loading of unnecessary images for the first screen, and prioritizing the loading of images required for the first screen

Because JavaScript will block DOM generation, and style files will block the execution of JavaScript, so in the actual project, we need to focus on JavaScript files and style sheet files, improper use will affect page performance.

long list data

If there are 10,000,000 pieces of data to be displayed, what optimization should be done to make the user experience better?

(1) Paging the data , using the principle of paging, the server only returns a certain amount of data each time, and the browser only loads a part of it each time.

(2) Use the lazy loading method to load part of the data each time, and load the rest of the data when needed.

(3) Using the array block technology , the basic idea is to create a queue for the items to be processed, then set the timer to fetch a part of the data every once in a while, and then use the timer to fetch the next item to be processed for processing, and then Set another timer.

(4) Virtual list , each time only the part that needs the viewport is rendered

Guess you like

Origin blog.csdn.net/weixin_43506403/article/details/129810886