The problem
Because we have some pages in onload to request data back and render the view, if we can request the data step before the page jump, we can request the data back earlier, the optimization effect depends on the page jump time.
demand
A pre-request approach is needed to take full advantage of the jump time and pre-request interface data while minimizing the retrofit costs of older projects. Since I’m currently in charge of a small program project that uses AXIos to request interface data, here’s just an example of how POST was modified in AXIos. Instead of making a new request, I’m rewriting the POST method to cache the interface that requires a prior request at request time and return the promise of the first request on the second request.
Specific steps
1. Transform the POST method
The HTTP file
Let instance = axios.create({// create an axios request instance // omit some code}); let { post } = instance; // Save the original post method let cache = {}; // request cache instance.post = function(... list) { let [url, data = {}] = list; If (cache[url]) {// Return a promise let pre = cache[url]; delete cache[url]; return pre; } if (data.pre) {// delete data.pre; cache[url] = post(... list) return cache[url]; } return post(... list); // Common request}Copy the code
2, use,
The page before the jump is the previous page
// omit some code... // This is the interface data to request in the next page, before the wx.navigateTo jump, and stored. $http.post('/act/activities/lucky:search', { activityId: 12 , pre: NavigateTo ({url: '${TYPE_TO_ROUTE_MAP[templateType]}? id=${activity.activityId}` }); }) // omit some code...Copy the code
The effect
Preloading is not used
Using preloading
The difference in width between the two red boxes indicates the amount of time before the interface data is requested, which is about 100ms. Because the following static resource address comes from the interface data, it is equivalent to reducing the blockage behind the resource load by about 100ms.
conclusion
The principle is to use small programs to jump this part of the time to request data in advance, so for poor performance of the phone will benefit more, although the developer tool seems to save about 100ms, but there are the following two limitations
- The data in the interface data that is pre-requested when the page is loaded
- You need to make a pre-request on the previous page and nextTick the jump
The revenue that led to this optimization was a bit of a chicken feed for the whole project.