当前位置:网站首页>Summary of small program performance optimization practice

Summary of small program performance optimization practice

2022-07-04 09:35:00 Dandelion_ drq

Project brief & problem

First, let's briefly introduce the project , It's a regular order applet .

The interface is as shown in the figure :
 Insert picture description here

On the left is the category menu , On the right is a long list , There are multiple categories of goods , After scrolling a single category, you can continue to scroll and switch to the next category , At the same time, when the classification menu on the left is selected, it will switch to the classification displayed in the current commodity list .

Considering the better user experience , And refer to meituan and other ordering procedures , The data of this product list is returned at one time . The current problem is , When the quantity of goods is large , The first rendering takes a long time , And the page will jam .

To optimize the direction

Logic optimization

Low voice bb: In fact, it is the original code ( For historical reasons ) It's too bad ……OTL

Put a picture first
 Insert picture description here

Low voice bb: I can't even watch small programs , Warning o(╯□╰)o

Wechat developer tools have warnings , And the prompt also has the location of specific code , So the key is this setData !!!

We can take a look at the official performance of small programs and setData Some suggestions for optimization .(https://developers.weixin.qq.com/miniprogram/dev/framework/performance/tips.html

Concrete practice :

1. setData You can't send too much data at one time , If the list is too long , You can render separately 【 For example, convert to a two-dimensional array , Render an array one at a time 】.

v1: Simple and rough version

//  Render one category at a time 
//  hypothesis goodsList Is a two-dimensional array 
goodsList.forEach((item, index) => {
    
    this.setData({
    
        [`goodsList[${
      index}]`]: item
    })
})

Writing like this will have a problem , The first screen rendering of the page is fast , But click on the page ( Such as additional purchase buttons ), The page will get stuck , Wait a moment before you react , Operation feedback delay is serious .
In fact, this is because , This cycle is a single setData The quantity has decreased , But it turns into a cycle many times setData, Let's look at the first screen , But in fact, other categories ( Other arrays ) Still rendering , The thread is still busy ,JS The thread has been compiling and rendering , Click events cannot be delivered to the logic layer in time , The logical layer can't transfer the operation results to the visual layer in time .

v2: Timer hack edition

since js The thread is busy rendering , Then we can force it to stop first . Hence the v2 Timer for hack edition .

//  Render one category at a time 
let len = data.goodsList ? data.goodsList.length : 0;
let idx = 0
let timer = setInterval(() => {
    
    if (idx < len) {
    
        that.setData({
    
            [`goodsList[${
      idx}]`]: data.goodsList[idx]
        });
        idx++
    } else {
    
        clearInterval(timer)
    }
}, 15);

Now the first screen rendering speed problem is solved , The problem of delayed response by clicking the button is also solved . The code is a little hack, Obsessive compulsive disorder o(╯□╰)o

v3: Big killer —— Virtual list

The principle of virtual list is simply to render only the current display screen area and the front n Screen and rear n Screen data , Use a separate field to save the current array to be displayed ( Is the current screen + front n screen + after n screen ), Recalculate the data to be displayed every time the list scrolls , Update this field , The page will be updated accordingly . This ensures that the number of element nodes on the page will not be too large , It can support the long list demand of a large amount of data .
More detailed principle and implementation, you can search by yourself , Not expanded here .

The official applet also has an open source virtual list component :recycle-view

2. setData It can support particle update , Assign to specific attributes .

For example, add purchase and other operations , The small number in the upper right corner of the product needs to be updated , It can be written like this :

this.setData({
    
    [`goodsList[${
      categoryIndex}][${
      goodsIndex}].num`]: goodsItem.num
})

3. Do not save data irrelevant to the page data, Do not use setData to update , because setData Trigger page rendering .

eg:

Page({
    
    data: {
    
        ...
    },
    //  Data irrelevant to page rendering 
    state: {
    
        hasLogin: false,
    },
    ...
})

//  When updating, assign values directly 
this.state.hasLogin = true

PS: Or you don't even need to mount to page Under the object , Save directly with ordinary variables .

4. Picture size optimization

In the long list, if the picture size is unlimited , A large number of large pictures will occupy a lot of memory , Could lead to iOS Client memory usage is up , This triggers the system to recycle the applet page . In addition to memory problems , Big pictures can also cause page switching stuck .

The solution is based on the size of the currently displayed image area , The size is just right (2 times -3 Times the figure ) Pictures of the .

It is suggested to use CDN, commonly CDN Service providers that provide image services will provide interfaces for cutting images , Then the interface only returns the original image link , The front end cuts the picture according to the parameters it needs . The specific practice of the front end can write public image processing methods , Or you can package the picture components yourself .

Common pictures are attached CDN Service provider image cutting API file :

5. Reduce unnecessary data requests

For example, you need to get the location when entering the order page , Then get the nearest store according to the location , The first two interfaces require requests ( The details can be based on business needs ), And finally, if the nearest store obtained is the same as last time , You don't need to get the store details and product data again .

Experience Optimization

1. Merge multiple in a short time loading Tips

Or the order page process , As mentioned above , You need to get the location interface when entering the page , Wait until the location interface returns the result, and then take the location value to obtain the nearest store , The last is to request store and product data .
These three interfaces are serial . At this point, if we pop up one for each interface loading Tips , Will appear loading Show for a while , disappear , Show it again for a while , Disappear again …… Such a phenomenon , Such an experience is not very good .
Suggestions can be made by encapsulating the request , And handle it uniformly in the request loading, To merge multiple requests that have been initiated multiple times in a short time loading.

eg:

let showLoadingTimer = null;
let showRequestLoading = false; //  Whether the tag is showing loading

/** *  encapsulation request * @param {*} {showLoading: Whether to display loading, options:request Parameters , Such as url,data etc. } */
function request({
    showLoading = true, ...options}) {
    
    //  Show request loading
    handleShowLoading(showLoading)

    wx.request({
    
        ...
        complete() {
    
            //  close request loading
            handleShowLoading(false)
        }
    })
}

/** *  encapsulation request loading *  If it is called many times in a short time showLoading, Will be merged and displayed together , Instead of everyone flashing  * @param showLoading */
function handleShowLoading(showLoading) {
    
    if (showLoading) {
    
        //  Show loading
        clearTimeout(showLoadingTimer);
        if (!showRequestLoading) {
    
            showRequestLoading = true;
            wx.showNavigationBarLoading();
            wx.showLoading({
     title: " Loading ", mask: true })
        }
    } else {
    
        // 200ms After closing loading
        showLoadingTimer = setTimeout(() => {
    
            showRequestLoading = false;
            wx.hideNavigationBarLoading();
            wx.hideLoading()
        }, 200)
    }
}

2. When the whole page is loaded for the first time, you can use the page loading Animation or skeleton screen , Optimize the loading experience .

3. Silent acquisition 、 Update data

For example, this order page every time onShow Will call the location interface and get the nearest store interface , But it doesn't show loading, Users are not aware , The experience is better .

Interface optimization

We need to pay attention to the granularity control of the interface .
Because sometimes merge interfaces , The front end can reduce one request , Experience better ; But sometimes if there is too much data in the interface , Response is too slow , You can consider whether some data can be acquired later , Let the main page content be rendered first , Split the interface according to this design .

For example, the order page in the project , It turns out that the shopping cart data and the detailed data displayed in the commodity specification pop-up window are all returned at one time at the store commodity acquisition interface , This interface was originally designed to return all products at once , It will cause too much data , And the back-end needs to query more tables . So get the shopping cart , And the product details interface are split into separate interfaces , The response time of getting the store product interface is reduced , Pages can also be displayed faster .

summary

In fact, many of the logic optimization and interface optimization mentioned above are details , Not too advanced technology , We can pay attention to . The optimization of experience requires front-end students to pay more attention to user experience and design knowledge besides front-end technology , And this is also a skill that a front-end with pursuit should have ……←_←
So …… Technology has a long way to go , Let's encourage each other

Reference article

https://developers.weixin.qq.com/miniprogram/dev/framework/performance/tips.html

原网站

版权声明
本文为[Dandelion_ drq]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202141425117347.html