Preface: Many students tend to confuse the applet life cycle with the page life cycle. These two should be different but related life cycles. So, use actual code and use official theory to explain this.

1. Applets life cycle

(1) First of all, the life cycle function of the applet is called in app.js, and the app (Object) function is used to register a applet. Accepts an Object parameter specifying the life cycle callback of its applet; Generally, there are onLaunch listener applet initialization, onShow listener applet display, onHide listener applet hiding and other lifecycle callback functions.

(2) The text is a little fuzzy to the concept, right? The best way to understand a concept is to actually do it. So, let’s see which onLaunch, onShow, and onHide is called first and when to start a small program.

OnLaunch () {console.log(‘onLaunch listens to applet initialization ‘); }

OnShow () {console.log(‘onShow listens for applet display ‘); }

OnHide () {console.log(‘onLaunch listener applet hide ‘); }

Open applets

Click the button in the upper right corner to hide the applet from entering again

(3) We can know that the life cycle function of the small program is called in the following order: onLaunch>onShow>onHide

2. Page lifecycle

(1) Page life cycle function is the life cycle function that you call every time you enter/switch to a new page. The Page(Object) function registers a Page. Accepts an Object parameter that specifies the page’s initial data, lifecycle callbacks, event handlers, and so on.

Page life cycle – screenshot from applets official website

(2) As usual, we use code to demonstrate the sequence of each page life cycle function.


  onLoad(options) {    console.log('onLoad listens for page load ');
  }

  onReady() {    console.log('onReady listening page first render completed ');
  }

  onShow() {    console.log('onShow listening page display ');
  }

  onHide() {    console.log('onHide listening page hide ');
  }

  onUnload() {    console.log('onUnload Listening page unload ');
  }

Copy the code

Page life cycle function

OnLoad >onReady>onShow; The onHide function is triggered when the page is hidden.

3, summary

Thus we know the order of “applets life cycle function” and “page life cycle function”; The sequence of events between the two is generally as shown in the figure above. The small program cycle function is first, and the page cycle function is triggered later. However, this is not absolute, for example, sometimes there will be a page onLoad function before the app onLaunch life cycle function of the situation, then you can put forward a question, that is, how to ensure that the onLaunch event of the app triggers a certain priority page onLoad event? This is the question we will address in our next chapter, “The Hard Tricks of Small Programs.”