Home  >  Article  >  WeChat Applet  >  Some practical tips for mini program performance optimization

Some practical tips for mini program performance optimization

hzc
hzcforward
2020-06-17 10:23:593577browse
Some practical tips for mini program performance optimization

Hello everyone, my name is Zhang Wenxuan, this is my 6th sharing

We all know that the quality of performance directly affects users experience. This article first discusses how to judge the performance of a small program page, and then focuses on several practical skills through specific cases. Finally, it discusses the role of the key value in rendering a list. Why key value is helpful for performance improvement.

Judge the performance of the mini program page

Due to the particularity of the mini program development environment, we cannot use chrome development tools or some mature performance testing tools like ordinary web pages ( For example, Lighthouse) to understand the performance of a page, but WeChat officially provides a performance scoring tool. Click here to view the tool details.

Experience rating is a function that scores the experience of a mini program. It will check in real time during the running of the mini program and analyze some areas that may lead to a poor experience. And locate the problems and give some optimization suggestions.

I will use a practical example later to show how to optimize page performance through this tool. Let’s first look at a score before our page optimization.

Some practical tips for mini program performance optimization

The data in setData is too large

Some practical tips for mini program performance optimization

ours There is a function of scrolling to the bottom to load. Before optimization, our approach was like this

<!--只阐述逻辑,非真实代码-->

// 1: 初始一个list,存储列表数据
data = startList
// 2: 监听滚动事件,滚动到底部获取新数据,并追加到list尾部,最后重新setData
onReachBottom:()=>{
    const {list} = this.data
    fetchNewData().then((res)=>{
        list.push(res.list);
        this.setData({list})
    }
}

I estimate that when most people are faced with scrolling a long list, the initial processing method is like this. If There is not much data, and only a few pages may not expose the problem too much. If there are too many pages, dozens or even hundreds of pages, the data in the list will become larger and larger, and the data in setData will become more and more every time. , so more and more nodes will be re-rendered each time the page is re-rendered, causing scrolling to the back and loading slower and slower. In addition, since the view rendering layer and the data logic processing layer of the mini program are separate and not on the same thread, from the user triggering the page interaction, to processing the data logic, to finally displaying the page, data needs to be transmitted to the view. Therefore, the mini program itself also has a limit on the data size, which cannot exceed 1M.

setData data path

How to solve it? The key in the mini program setData supports the writing method of data path, such as

let o = obj;
this.setData({ 
  'o.属性':value
})

或者let a = array;
this.setData({ 
  'array[0].text':value
})

, so we can transfer the data to the view layer in batches through the writing method of data path, reducing the data of one-time setData. size. The specific writing method is as follows

// 1.通过一个二维数组来存储数据let feedList = [[array]];

// 2.维护一个页面变量值,加载完一次数据page++let page = 1

// 3.页面每次滚动到底部,通过数据路径更新数据
onReachBottom:()=>{
    fetchNewData().then((newVal)=>{
        this.setData({
            ['feedList[' + (page - 1) + ']']: newVal,
        })
    }
}
// 4.最终我们的数据是[[array1],[array2]]这样的格式,然后通过wx:for遍历渲染数据

There are too many image requests initiated in a short period of time (image lazy loading)

This should be easy to understand, that is, when rendering the page, it is sent all at once Too many image requests lead to too many http requests being initiated at the same time. HTTP connections are very time-consuming, especially if so many are initiated at once, and there are limits to the number of http links initiated at one time, such as the Chrome browser. There is a limit of 6 at a time.

So when rendering the page, we do not load images that are not within the view range. Only the elements that appear within the view range will be rendered again.

The conventional approach is to get the position of the element through getBoundingClientRect(), and then compare it with the scroll position of the page. If it appears in the view, img will be displayed. This method has two problems

  • The getBoundingClientRect() method call itself can easily cause page rearrangement
  • The monitoring scroll event itself is frequently triggered. Although it can be reduced by throttling, it is still easy to increase unnecessary code processing

IntersectionObserver

In fact, WeChat provides IntersectionObserverObject.

IntersectionObserver object, used to infer whether certain nodes can be seen by users and what proportion can be seen by users

Through this API we There is no need to actively monitor the position of elements. At the beginning of page rendering, specify the elements that need to be monitored through this API, and the system will automatically monitor the position of the elements.

let data = list;

<img class="img-{{index}}" wx:for="{{data}}"></img>

data.forEach((item,index)=>{
    this.createIntersectionObserver().relativeToViewport.observe(`.img-${index}`,res=>{
            if (res.intersectionRatio > 0){
            this.setData({
                item.imgShow:true
            })
        }
    })
}

The intersectionRatio value is greater than 0, indicating that the element appears in the view. SetData data is reset to display the picture component.

The picture is too large and the display area is too small

This problem means that the picture size is too large, and the size we display on the page is too small. The picture size is too large. Requesting images becomes slower, resulting in slower page rendering.

CDN image processing

For the images on the page, it is best to store the images on the cdn server. One is to make full use of the cdn cache to speed up the request. The other is that CDN can perform certain processing on images, such as cropping. Our company responds to image processing through CDN, and then tells the CDN server what size image is needed when requesting the image, and the CDN server responds to the corresponding size image.

The role of key value in list rendering

Key value can improve list rendering performance when rendering list. Why? First of all, you have to think about how the mini program page is rendered, which is mainly divided into the following steps:

  1. Construct the wxml structure document into a vdom virtual number
  2. The page has new Interact, generate a new vdom number, and then compare it with the old number to see where there are changes, and make corresponding modifications (delete, move, update value) and other operations
  3. Finally, render the vdom into a real page The role of the structure

key value is in the second step. When the data changes trigger the rendering layer to re-render, the components with the key will be corrected, and the framework will ensure that they are reordered, not re-rendered. Created to ensure that the component maintains its own state and improves efficiency when rendering the list.

If the key value is not specified, it will be processed by the index of the array by default, which will cause confusion in the values ​​​​of some input box components such as input.

Some practical tips for mini program performance optimization

Relevant test code can be viewed at: wxkey

You can see

  • No Add key and append elements to the end of the array. Previously rendered elements will not be re-rendered. But if an element is inserted at the head or in the middle, the entire list is deleted and re-rendered, and the value of the input component is also confused, and the value is not updated normally.
  • Add key, in the array When elements are inserted at the end, middle, or head, other existing elements will not be re-rendered, and the values ​​​​can be updated normally

Therefore, When doing list rendering , if the order of the list changes, it is best to add the key, and do not simply use the array index as key.

Finally look at our results:

Some practical tips for mini program performance optimization

Experience code:

Some practical tips for mini program performance optimization

I hope my sharing today can give you some inspiration for optimizing your mini program page and create a page with better and smoother performance.

Finally, if you like my article, please click to follow. I will share some of my views and thoughts from time to time, so that I can grow and continue to learn with everyone.

Recommended tutorial: "WeChat Mini Program"

The above is the detailed content of Some practical tips for mini program performance optimization. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete