Home  >  Article  >  WeChat Applet  >  How to make your mini program run fast

How to make your mini program run fast

王林
王林forward
2021-03-15 09:52:221664browse

How to make your mini program run fast

Preface

I have seen an article before about improving the speed of mini program application. The article mainly talks about how to implement the mini program to request before triggering the page jump. The protocol uses the short 200~300ms time to jump to the page to obtain the data and render it on the page, so that the data can be preloaded in the mini program page.

Through this technology, users’ waiting time can be shortened and the user experience can be greatly improved. Since that article did not give the implementation method, but only explained the technical principles, this article will explain the technical implementation method for everyone.

Framework advantages and disadvantages

Advantages:

  • Preload the data of the next page, which improves the page loading speed, lightweight protocol ( Data can be received in about 200~300ms), which allows the data to be loaded instantly after the mini program page is opened, and there is almost no empty page.

  • Keep the code of the same business in one class without destroying the project structure.

  • The amount of code is very small, and it has very little impact on the original business.

  • Want to delete preloading after implementing preloading? Just delete a string in the implemented class.

Disadvantages:

  • You need to replace setData with $setData according to the situation

  • Requires a developer Be very clear about what the context of each situation is.

  • If your protocol is very time-consuming, reaching more than 400ms, the effect of using this optimization method will not be obvious.

  • Some netizens found that this project cannot run in small programs that use components, so if you use components, you should not use this project directly. However, it is still recommended that you absorb the ideas of this project. After all, thinking is very important for engineers at work.

I won’t show you the final effect here. Interested friends can try it on their own.

(Free learning video sharing: php video tutorial)

How to integrate

Important statement: My applet follows the ES6 standard Written, it uses class extends and destructuring assignment, etc. If you don’t understand it, please learn ES6! ! If your project uses ES5, then read the follow-up articles carefully and understand the core idea of ​​preloading technology. If you understand the core idea, write it out in minutes, right~ ~

First of all, you have to There is a base class CommonPage

Every Page class in the applet inherits this base class, which facilitates unified management.

For example, the following IndexPage page

// pages/index/index.js
import CommonPage from "../CommonPage";
class IndexPage extends CommonPage {
    constructor(...args) {
        super(...args);
        this.data = {
            testStr: 'this is the firstPage'
        }
    }

    onLoad(options) {
    }
}

Page(new IndexPage());

IndexPage is the first page and does not need to be preloaded. SecondPage is the second page. Let’s simulate the preloading method of SecondPage.

What you see next, this.$route() this.$put() this.$take() this.$resolve() this.$reject() and so on, are all base classes. method implemented in.

1. Add a jump button to the IndexPage page.

<!--index.wxml-->
<view class="container">
    <view bindtap="toSecondPage" hover-class="press-style" class="normal-style" hover-stay-time="100"> 闪电加载第二个页面</view>
    <view>300毫秒 闪电加载方式</view>
</view>

Note: The class="normal-style" hover-stay-time="100" added here is very important. If the click state is not added, the experience will be greatly affected.

2. Add a preloading-specific jump method to the IndexPage page.

 toSecondPage = function () {
        // this.$route是预加载的页面跳转方式,以wx.navigateTo方式跳转。这个方法是在CommonPage中实现的。
        this.$route({path: &#39;../second/second&#39;, query: {count: 10, title: &#39;这是第二个页面&#39;}, clazzName: &#39;SecondPage&#39;});
		
		// 这是小程序原生的普通加载方式
        // wx.navigateTo({
        //     url: &#39;../second/second?count=10&title=这是第二个页面&#39;
        // })
    }

this.$route({path, query, clazzName});The parameter meaning of this method is:

  • path: page path, supports absolute path and relative path path.

  • query: Parameters that need to be passed. This is an object type.

  • clazzName: The class name of the page that needs to be jumped. I’ll talk about this later when I introduce SecondPage.

In fact, you may ask, since there is a path, why do you need clazzName? This issue will be discussed in detail when introducing the technical principles, which is the next article.

At this point, if you also use ES6 specifications to implement classes, you can see that in IndexPage, you only need to change the jump method to this.$route({path, query, clazzName} ); that’s it.

3. Add a preload-specific initialization method to the SecondPage page.

// pages/second/second.js
import CommonPage from "../CommonPage";
class SecondPage extends CommonPage {
    constructor(...args) {
	    //super(...args)一定要写,他会将clazzName与下面的data进行合并。
        super(...args);
        //这个$init(obj)中注入的obj就是页面初始时的data
        super.$init({
            arr: []
        });
    }

    $onNavigator(query) {
	    //这里的query是从this.$route中传递来的query
        console.log(&#39;闪电️加载时接收到的参数&#39;, query);
        this.$put(&#39;second-data&#39;, this.initData.bind(this), query);
    };
	
    initData = function (query, resolve, reject) {
	    //这里的query是在this.$put()中传递过来的
	    //resolve在协议成功时回调
	    //reject在协议失败时回调
	    //模拟网络请求
        setTimeout(() => {
            if (typeof query.count === "string") {
                query.count = parseInt(query.count);
            }
            this.data.arr.splice(0, this.data.arr.length);
            for (let i = 0; i < query.count; i++) {
                this.data.arr.push({id: i, name: `第${i}个`, age: parseInt(Math.random() * 20 + i)})
            }
            this.$setData(this.data);
            this.$resolve(this.data);//或者 resolve(this.data);只有调用了resolve或者reject方法,才能在this.$take()的then()方法中获取到值。
        }, 300);
    };

    onLoad(options) {
        const lightningData = this.$take(&#39;second-data&#39;);
        if (lightningData) {
            lightningData.then((data) => {
	            //成功回调,resolve(data)调用时触发 data就是resolve传递的参数
                this.$setData(data);
            },(data, error)=>{
	            //失败回调,reject(data, error)调用时触发,data和error是reject传递的参数。
            });
            return;
        }
        this.initData(options);
    }
}
//这里注入的clazzName: &#39;SecondPage&#39;,与this.$route({path, query, clazzName});中的clazzName名称与其一致即可
Page(new SecondPage({clazzName: &#39;SecondPage&#39;}));

Probably the following steps:

  • This class needs to inject clazzName when new, this.$route({path, query, clazzName}); The clazzName name in it can be consistent with it.

  • You need to inject a new life cycle function into SecondPage, which is the preloading method. When executing this.$route, whatever is the clazzName you pass in this.$route, the framework will automatically find a matching class and call the $onNavigator method of that class.

  • Call this.$put(key, fun, query) in $onNavigator. The parameters are the key, the asynchronous request method, and the parameters of the asynchronous request method respectively.

  • Replace this.setData with this.$setData() in the asynchronous request method, and use this.$resolve(data) or this.$reject(data,error) to call back successfully or fail.

  • Use this.$take(key).then(success,fail) in onLoad to obtain the asynchronous result, which corresponds to the resolve and reject callbacks respectively. If you do not use preloading, or preloading fails, then this.$take(key) method returns empty, so you can determine whether preloading is used to enter the page!

By doing this, the protocol of the next page is sent out before jumping, and the code of the same business is kept in one class without destroying the project structure!

After implementing preloading, if you don’t want to use preloading, you only need to delete the clazzName injected when new SecondPage()!

Related recommendations: Mini Program Development Tutorial

The above is the detailed content of How to make your mini program run fast. For more information, please follow other related articles on the PHP Chinese website!

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