当前位置:网站首页>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 :
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
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
边栏推荐
- Implementation principle of redis string and sorted set
- Golang 类型比较
- Ultimate bug finding method - two points
- Daughter love in lunch box
- Problems encountered by scan, scanf and scanln in golang
- PHP book borrowing management system, with complete functions, supports user foreground management and background management, and supports the latest version of PHP 7 x. Database mysql
- 2022-2028 global seeder industry research and trend analysis report
- Report on the development trend and prospect trend of high purity zinc antimonide market in the world and China Ⓕ 2022 ~ 2027
- Global and Chinese market of sampler 2022-2028: Research Report on technology, participants, trends, market size and share
- mmclassification 标注文件生成
猜你喜欢
Jianzhi offer 09 realizes queue with two stacks
PHP is used to add, modify and delete movie information, which is divided into foreground management and background management. Foreground users can browse information and post messages, and backgroun
2022-2028 global special starch industry research and trend analysis report
2022-2028 global probiotics industry research and trend analysis report
SSM online examination system source code, database using mysql, online examination system, fully functional, randomly generated question bank, supporting a variety of question types, students, teache
C # use gdi+ to add text with center rotation (arbitrary angle)
PHP student achievement management system, the database uses mysql, including source code and database SQL files, with the login management function of students and teachers
How should PMP learning ideas be realized?
Leetcode (Sword finger offer) - 35 Replication of complex linked list
2022-2028 global intelligent interactive tablet industry research and trend analysis report
随机推荐
Target detection -- intensive reading of yolov3 paper
About the for range traversal operation in channel in golang
2022-2028 global protein confectionery industry research and trend analysis report
Web端自动化测试失败原因汇总
PHP is used to add, modify and delete movie information, which is divided into foreground management and background management. Foreground users can browse information and post messages, and backgroun
Are there any principal guaranteed financial products in 2022?
Solution to null JSON after serialization in golang
《网络是怎么样连接的》读书笔记 - Tcp/IP连接(二)
Go context 基本介绍
26. Delete duplicates in the ordered array (fast and slow pointer de duplication)
Global and Chinese market of air fryer 2022-2028: Research Report on technology, participants, trends, market size and share
C # use gdi+ to add text with center rotation (arbitrary angle)
PMP registration process and precautions
LeetCode 74. Search 2D matrix
Les différents modèles imbriqués de listview et Pageview avec les conseils de flutter
Launchpad x | mode
《网络是怎么样连接的》读书笔记 - 认识网络基础概念(一)
Investment analysis and prospect prediction report of global and Chinese high purity tin oxide Market Ⓞ 2022 ~ 2027
2022-2028 global tensile strain sensor industry research and trend analysis report
UML 时序图[通俗易懂]