Historical review:
- Wechat applets custom component – table component is coming
- Realize “Dingdingclocking” through wechat mini program
- Make a note of the subcontracting of wechat small program project and the pre-downloading of subcontracting
- Micro channel applet practice
This article is mainly according to the official WeChat applet optimization Suggestions and “2018 WeChat season 7 Shanghai public class, special small program, the performance of the optimized scheme, our small application programs targeted performance optimization practice, record process, convenient later viewing, but also hope I can help to other friend, completes the performance optimization. After all, performance optimization is all about a better user experience.
The optimization with the green flag is practiced
Common performance problems with applets
- Why is this little program so slow?
- Why isn’t this little program working? It’s stuck?
- Why does the applet have a delay when cutting the page?
- Why to click did not respond, hang up?
These problem scenarios all reflect the performance problems of applets, which directly affect the user experience.
How can applets be optimized for performance?
The official recommendation is to optimize from these two aspects:
- Startup performance optimization
- Rendering performance optimization
Startup performance optimization
Small program in the entire startup process, generally need to complete several tasks:
- 1. Prepare the operating environment (handled by wechat itself)
- 2. Download, inject, and execute the corresponding applets code package
- 3. Render the home page of the applet
Developers can optimize the startup performance of applets in 2,3.
1. Code package size optimization
When the applet is first opened, it downloads and executes the code package, which takes more time as the package size increases. The following options can be adopted:
The subcontract
Use of the subcontract
For developers, it can make small programs have smaller code volume, bearing more functions and services; For users, they can open small programs more quickly and use more features without affecting startup speed.
It is recommended that developers divide the function into several subpackages and only load the subpackages corresponding to the function when it is needed.
practice
One of our small programs was developed more than two years ago. We didn’t think about this at the beginning of the design, nor did we have the ability to subcontract small programs. Well, here comes the question.
It is clearly stated in the development document of wechat small program that the package size of all small programs must be limited to 2M. If the package size exceeds 2M, it cannot be previewed normally in the developer tools, let alone uploaded and distributed. Solutions to the problem:
To image compression static resources, because of the small program compression algorithm for image compression, as a result, the round of images compression, and the repeated use of images, the public, although the official images, it is recommended to use network static resource, but also need to maintain the trouble, gave up.
A wave of purging of deprecated pages in the project, as well as unused third parties.
Many projects are optimized by webpack into different subcontracts and lazy loading of resources. Small programs also provide this function: subcontract. According to the principle of function division, the author places pages and logic under the same function in the same directory and becomes a subcontract.
After subcontracting:
Note: 1. Customize third-party components, which need to be placed in the main package. The miniprogram_npm file will be directly typed into the main package. 2. Small program TAB switch page, must be placed in the main package.
Subcontract predownload
The subcontract pre-download is designed to solve the problem of delay when entering the subcontract page for the first time. If the subcontract is downloaded before the user enters the subcontract page, the delay in entering the subcontract page can be minimized.
practice
The user performs an operation and then downloads subcontracting. The delayed operation leads to poor user experience, so the author sets subcontracting pre-download for the subcontracting above. In the app.json file:
"preloadRule": {
"pages/work/index": {
"network": "all",
"packages": [
"package-work",
"package-field-statistics"
]
},
"pages/appeal/index": {
"network": "all",
"packages": [
"package-appeal"
]
}
},
Copy the code
It is not recommended to pre-download all the packages at once, as this can also cause performance problems.
Independent of the subcontract
Some scenarios in applets (such as advertising pages, active pages, payment pages, etc.) are usually not very complex and relatively independent, and have high requirements on startup performance. With independent subcontracting, you can operate independently of the main package and other subcontracting. There is no need to download the main package when entering the applet from the standalone subcontracting page.
Developers are advised to place some of the pages that require high startup performance into a special separate subcontract.
practice
There is no suitable scenario in the project, which has not been implemented.
2. First screen rendering optimization
1. Request first-screen data in advance
Most applets rely on server interface data to render the home page. The interface requests are placed in onLoad, not onReady, the page’s lifecycle.
practice
Listen to page load, verify login, request page data
OnLoad: function (options) {app.checkauth ((error, token) => {if (error) {return})},Copy the code
2. Cache request data
The applets provide wx.setStorageSync and other asynchronous reading and writing capabilities of the local cache. Data is stored locally and returned faster than network requests.
practice
After a successful login, the user’s token and user information can be cached to the local PC. Remember to cache the information when you log out, go to ๐.
/** * Set the local token cache *@param {Object} Data returned by the session server *@param {String} Session. access_token Access token *@param {String} Session. refresh_token Refreshes token *@param {String} Session. expiRES_in Validity period, in seconds */
export function set(session) {
const localSession = Object.assign({}, session, {
expires_timestamp: getExpireTimestamp(session.expires_in)
});
wx.setStorageSync(SESSION_KEY, localSession);
_token = session.access_token;
}
export function clear() {
wx.removeStorageSync(SESSION_KEY);
clearTimeout(refresh_timer);
_token = null;
}
Copy the code
3. Simplify the first screen data
It is recommended that developers delay the request of non-critical rendering data to shorten the network request delay. Data irrelevant to view layer rendering should not be stored in data as far as possible to avoid garbage data transmission and accelerate the completion time of first screen rendering.
practice
If id is not needed in the rendering layer, it is not necessary to define id in data:
Data: {id: ' ', //... }, onLoad: function (options) {this.setData({id: options.id}) //... Data: {//... . }, app.checkAuth((error, token) => { const id = options.id === undefined ? '' : options.id; this.id = id })Copy the code
The data returned by the interface should be processed instead of being directly fed to data to reduce the double-thread return of redundant data. It’s also part of an optimization to streamline the first screen.
4. Avoid blocking render
OnLaunch, app.onshow, Page. OnLoad, Page. OnShow, page. For example, wx.setStorageSync and wx.getSystemInfoSync.
practice
This was not used in the project and was prescient. ๐
Rendering performance optimization
The view layer of the applet currently uses WebView as the rendering carrier, while the logic layer uses a separate JavascriptCore as the runtime environment. In terms of architecture, WebView and JavascriptCore are independent modules and do not have channels for direct data sharing. Currently, data transfer between the view layer and the logical layer is actually implemented through evaluateJavascript provided on both sides. That is, the data transmitted by the user needs to be converted into a string for transmission. At the same time, the converted data content is spliced into a JS script, and then transmitted to the independent environment on both sides by executing the JS script.
The evaluateJavascript execution is affected in many ways, and the arrival of data to the view layer is not real-time.
** Common setData operation error **
1. Frequent setData visits
There are two consequences:
- Under Android, the user will feel stuck when sliding, and the operation feedback delay is serious, because JS thread has been compiling and executing rendering, which fails to transfer the user operation events to the logic layer in time, and the logic layer cannot transfer the operation processing results to the view layer in time;
- Due to the busy WebView JS thread, the communication time from the logic layer to the page layer increases. The data message received by the view layer has passed several hundred milliseconds since it was sent, and the rendering result is not real-time.
practice
At present, the project code is still more standard, we did not call setData as a common object, know that each use requires communication between two threads, WebView to render. Wow, that’s great.
2. SetData passes a lot of new data each time
From the underlying implementation of setData, we can see that our data transfer is actually a process of evaluateJavascript script. When the amount of data is too large, the compilation and execution time of the script will increase and the WebView JS thread will be occupied.
practice
At present, the amount of data in each interface is not large, and the magnitude of data has not reached the level that affects the execution of steps. If necessary, we can optimize it.
3. Perform setData on the background state page
When the page enters the background state (invisible to the user), it should not continue to setData, the rendering of the background state page is not felt by the user, and the background state page to setData will also preempt the execution of the front page.
practice
There is A timer on page A, page B is opened at this time, the timer of page A is still running, continue to seize the resources of page B, page B is stuck, but the performance problem is not caused by page B, this problem is not easy to troubleshoot. I hope we can do a complete person, timer need not to clear. In the following demo, the timer should be cleared at onHide. Remember to remember ๐
/** * lifecycle function -- listens for page display */
onShow: function () {
clearTimeout(getTodaytime)
this.updateNowTime()
},
/** * life cycle function - listen for page hiding */
onHide: function () {
// Cancel the timer to prevent small programs from running out of memory and crashing
clearTimeout(getTodaytime)
},
updateNowTime() {
getTodaytime = setInterval(() = > {
const myDate = new Date(a);const hours = myDate.getHours())
const minutes = myDate.getMinutes())
const seconds = myDate.getSeconds())
const newTime = hours + ':' + minutes + ':' + seconds;
this.setData({
newTime: newTime
})
}, 1000)},Copy the code
2. User events are used improperly
- Excessive use of bindTap and bindCatch
- Improper use of onPageScroll
practice
This event is not used in the project display.
3. Use custom components
In scenarios that require frequent updates, updates to custom components occur only within the component and are not affected by the complexity of content in other parts of the page.
practice
Our project applet punch card function needs to show the current time: hour, minute and second, which is realized by timer here and needs to update setData frequently. Here, it is suitable to extract the timer as a component, so that it can update data inside the component without affecting other parts of the page.
conclusion
Applets start loading performance:
- Controls the size of code packages
- The subcontract to load
- The first screen experience
Applet rendering performance:
- Avoid improper use of setData
- Use event communication wisely
- Avoid improper use of onPageScroll
- Optimizing view nodes
- Use custom components
Note: The PPT in this article is from “2018 wechat Open Class 7th Season Shanghai Station ยท Small program Special Session”.
reference
- 2018 wechat Open Class 7th season Shanghai station ยท Small program special session
- Micro channel applets – optimization
- Wechat applets – tool plug-ins – experience rating
- Micro channel small program rendering performance tuning
- Micro channel small program performance optimization program – make your small program so smooth
- [wechat mini program] performance optimization