Introduction and common methods of front-end performance optimization (2)

This is a front-end blogger without routines. He is keen on all kinds of front-end oriented operations. He often writes wherever he thinks. If you are interested in technology and front-end effects, you can leave a message~ The blogger will step on the pit for everyone after seeing it. the ~

Homepage: Oliver Yin's homepage

Motto: Get up when you fall~

Table of contents

I. Introduction

2. Overview of the content of this article

3. Performance optimization

3.1 Loading performance optimization

3.2 Build Optimization

3.2.1 javascript compression

3.2.2 CSS Compression

3.3 Rendering optimization

3.3.1 Reduce backflow

3.3.2 Reduce the number of layouts

3.3.3 Anti-shake and throttling

3.4 Cache performance optimization

3.4.1 Browser cache

V. Summary


I. Introduction

Recently, our company’s small partners encountered some problems in the project, which were related to performance, so we discussed some front-end performance optimization methods, plus some of our own daily study notes, and after reorganization, we have this article~

Read it patiently, you may gain something~

2. Overview of the content of this article

This article first specifically shares some performance optimization points or methods that may be encountered in daily development, difficulty: intermediate ;

3. Performance optimization

3.1 Loading performance optimization

The most common loading performance optimization is the optimization of the loading time of the first screen . If it is a single-page project such as a Vue/React project, the site will be slower when it is loaded for the first time, because the entire The front-end project is sent to the browser at once...

Excessive waiting time will exhaust the patience of the user, and may leave the site directly during the waiting process, so the optimization of the first screen is often particularly important!

Take station B as an example, as shown in the figure below, we can see that when the homepage of station B is opened, 83 items are requested, with a total resource size of 2.1M

But as the screen scrolls, more and more resources will be loaded, as follows

This is lazy loading technology,

To put it bluntly, only the content of the visible area is displayed, and the content beyond the visible area is not loaded when it is not displayed. As for why there is an offset, the reason is that if it happens to appear on the page, it will be loaded. It will be a bit late, and users can’t see the content they want to see at the first time, so we made an advance amount. Once the element reaches the offset area, then we think that the user will see it immediately, and it should be actively loaded~

The implementation method is not complicated. Take the image resource as an example. The image address is placed on the custom attribute by default. Only when the image enters the offset area, the value in the data-src on the image is actively assigned to the src;

// 代码层面
<img data-src="图片地址" src="" />

In addition, for single-page applications such as Vue/React, we can operate as follows

<!DOCTYPE html>
<html lang="en" id="htmlRoot">
  <head>
    <title><%= title %></title>
    <link rel="icon" href="/favicon.ico" />
  </head>
  <body>
    <div id="app">
    	// lodaing动画效果
      <div class="app-loading">
        <div class="app-loading-wrap">
          <img src="/resource/img/logo.png" class="app-loading-logo" alt="Logo" />
          <div class="app-loading-dots">
            <span class="dot dot-spin"><i></i><i></i><i></i><i></i></span>
          </div>
          <div class="app-loading-title"><%= title %></div>
        </div>
      </div>
    </div>
  </body>
</html>

Add the loading animation effect to the top-level element. We need to know that Vue/React will actively cover the content in the top-level element when the resource is loaded. By using this feature, we still have The loading animation, let the user wait for a while~

3.2 Build Optimization

Before that, let's ask a question: Why can performance be improved through construction optimization?

We know that the process of requesting resources after establishing a request, how to quickly request all resources is a process worthy of attention, so how to quickly request all resources? In fact, there are two points:

  • The first one is: resource compression , reducing the volume of resources, then the transmission time will naturally decrease;
  • The second is: resource merging , merging multiple resources together, one request is equivalent to requesting multiple resources, which can naturally reduce the transmission time;

In order to achieve these two points, it is construction optimization, taking webpack as an example (although new construction tools such as vite are becoming more and more popular, the huge usage of webpack is still the mainstream....)

3.2.1 javascript compression

There are roughly several configurations on webpack that can achieve the effect of compression:

(PS: When using terser-webpack-plugin for compression, this plugin will perform multi-threaded compression by default to improve the compression speed)

3.2.2 CSS Compression

Here is a point to note, do not use style-loader to embed css directly into html, but should be a separate css file , this is very important, the reason is also very simple, css resources cannot be loaded in parallel, so it will reduce rendering performance;

Therefore, we can use the plug-in: min-css-extract-plugin This plug-in extracts and separates CSS codes. After configuration, it roughly looks like this:

const CSSMinimizerPlugin = require("css-minminzer-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports={
	// 其他配置
	optimization:{
		minimize:true,
		minimizer:[new CSSMinimizerPlugin()]
	},
	plugins:[new MiniCssExtractPlugin()]
}

3.3 Rendering optimization

The main part of the first two optimizations is in the http request part. This part is the process of rendering the resource into DOM in the browser rendering process after the resource request arrives. This process roughly has the following specific details:

Through this general process, we found that the rendering of the interface is actually quite troublesome. It is best not to move these rendered DOM nodes, but in fact, it is impossible to move. Isn’t the user’s daily work just To interact with the interface, once the interaction starts, the DOM nodes will naturally undergo various changes....

3.3.1 Reduce backflow

For interface changes, we can divide them into two categories: redrawing and reflow . I believe that the friends must be familiar with these two points, so I won’t introduce them more. Compared with redrawing, reflow has a greater impact . It affects The geometric properties of many nodes on the page, so the entire page needs to go through the above process again, and the impact on performance can be imagined;

Therefore, there is actually only one optimization purpose for this part: redrawing consumes more performance and minimizes reflow operations ; roughly the modification of the following attributes will affect reflow:

  • Changes in geometric properties , such as: width, height, padding, margin, left, right, etc.;
  • The DOM tree changes , such as adding, modifying, and deleting dom nodes;
  • Get specific attribute values , such as offsetTop, scrollTop, etc.;

3.3.2 Reduce the number of layouts

It is worth noting that we prohibit the following writing :

const dom = document.querySelector(".dom");

dom.style.width="100px";
dom.style.height="100px";
dom.style.border="1px solid #000000";

This way of writing modifies the geometric properties of the DOM three times, so the interface will be re-layouted three times . This kind of thing is not advisable. The reasonable way is to add a class to the dom

const dom = document.querySelector(".dom");
dom.classList.add('new-style');

.new-style{
  width:100px;
  height:100px;
  border:1px solid #000000
}

This way of adding class  will only re-layout once ;

3.3.3 Anti-shake and throttling

And for some events, such as

Events like this need to be anti-shake and throttling . If these events are triggered frequently, it will inevitably cause the page to shake and freeze. In essence, it is not to reduce the triggering of events, but to reduce the number of executions triggered by callback functions . Their usage scenarios are also a bit different:

  • Throttling : The meaning of throttling is to execute a function at a fixed interval. For example, the keyboard is pressed 10 times within 1 second, but we limit the request to only 1 request per second through throttling, which can greatly reduce requests frequency;
  • Anti-shake : The meaning of anti-shake is that high-frequency triggers in a short period of time will eventually be combined into one. Will go to request, once there is a new text input within 1 second, it will clear the request event and no longer trigger;

There are many anti-shake and throttling codes on the Internet, including lodash, which is also ready-made and packaged, so I won’t introduce it~

3.4 Cache performance optimization

The first is to deal with repeated requests , and the resources that have been obtained must be reused, because repeated requests will consume network bandwidth, thereby affecting user experience;

3.4.1 Browser cache

Browser caching is divided into mandatory caching and negotiation caching :

  • Mandatory caching : Check the cache field when requesting, and return the resource directly from the browser's local cache if it has not expired ;
  • Negotiation cache : before the browser uses the local cache, send a request to the server to determine whether the local cache has expired ;

Usually, we generally use this process to prioritize caching

V. Summary

This article introduces the various points of performance optimization in detail.

  • The purpose of loading optimization is to reduce the loading time of the first screen by reducing http requests and lazy loading technology;
  • The purpose of construction optimization is to reduce the volume and quantity of resources, and rationally use mainstream construction tools, such as webpack, to merge and compress resources;
  • The purpose of cache optimization is to avoid repeated requests, but the cache strategy needs to be carefully considered, after all, there are advantages and disadvantages;
  • Rendering optimization , the purpose is to reduce high-performance operations, such as reducing redrawing and reflow, reasonable code, and timely release of resources;

Guess you like

Origin blog.csdn.net/zy21131437/article/details/132185911