# Page switching optimization

The performance of page switching affects the coherence and fluency of user operation, and is an important part of the performance of Mini Program.

# 1. The process of page switching

In order to optimize the performance of page switching, it is necessary to first understand the process of page switching in the Mini Program. The page switching process is shown in the figure:

Developers can usewx.getPerformanceIn the interface entryType for navigation,name for Route PerformanceEntry) to get the time spent switching pages.

When the target page for the switch has finished loading (for example, the route type is NavigateBack, or switchTab To a loaded page), there is no need to carry outView Layer Page InitializationandTarget Page Rendering,Logical Layer Page InitializationIt will also be simpler, as shown in the figure below:

# 1.1 Trigger page switching

The process of page switching begins with the user triggering the page switching.

Trigger time correspondence PerformanceEntry(Route) to hit the target startTime。

Page switching may be triggered by the following classes of actions:

  • Mini Programs API calls: Developers, based on user actions, call [wx.navigateTo]((wx.navigateTo ))、[wx.navigateBack]((wx.navigateBack ))、wx.redirectTowx.reLaunchwx.switchTab etc. API。
  • The user clicks <navigator> Component for page switching.
  • User Clicks Native UI Trigger: For example click TabBar (Custom tabBar Except), click on the upper left cornerReturn to the home pageButton, click the system return key or left slide back, etc.
  • Automatic when Mini Program hot start reLauch:[Mini Program hot start]((runtime/operating-mechanism#_3 - Mini Program hot start page))of B Class scene

At present, the latter two cases are temporarily unable to obtain an accurate trigger time, PerformanceEntry(Route) of startTime and navigationStart Consistent.

# 1.2 Load sub-packages (if any)

If the target page of the page switch is in the subcontract, the page switch needs to download the subcontract and inject the execution subcontract at the logical level. JS Code.

During the life of the Mini Program, each subcontract is injected only once at the logical level.

# 1.3 View Layer Page Initialization

Each page of the Mini Program view layer is composed of separate WebView Rendered, so a new page is required when switching WebView Environment. View layer page initialization does the following:

  • create WebView
  • Small Program Base Library Injected into View Layer
  • Common code injected into the main package (except independent sub-packages)
  • If the page is in a subcontract, inject the subcontract's public code
  • Inject Page Code

In order to reduce the time required to initialize the view-level page, after the page is rendered, the necessary preloads are usually carried out for page switching. The preload mainly does the following:

  • create WebView
  • Small Program Base Library Injected into View Layer
  • Inject the public code of the main package (if the primary package is already local)

If the page switches too quickly, or the preloaded environment is reclaimed, you need to recreate the environment when the page switches.

If you have a preloaded environment when you switch pages, you can greatly reduce the time required to switch pages.

This stage is not required when the target page of the switch has been loaded.

# 1.4 Logical Layer Page Initialization

Complete the subcontract loading and WebView Once created, the client dispatches routing events to the base library.

When the base library receives an event, it initializes the logical level of the page, including the onHide/onUnloadPage component tree initialization, update the page stack and generate initial data to send to the view layer, and in turn trigger the onLoad, onShow Life cycle. If enabledInjection on demand, this phase also injects the page code.

Time Correspondence of Base Library Receipt Events PerformanceEntry(Route) to hit the target NaviationStart, corresponding PerformanceEntry(firstRender) The start time.

When the switching target page has been loaded, there is no need to initialize the page component tree and send the initial data. onLoad

# 1.5 Target Page Rendering

The first rendering of the page is triggered when the target page for the page switch does not exist.

After completing the view layer code injection and receiving the initial data sent by the logic layer, combining the page structure and style information obtained from the initial data and the view layer, the Mini Program frame will render the page and trigger the onReady Events.

Visual layer rendering completed, trigger the page onReady The time of the event, corresponding to the PerformanceEntry(firstRender) The end time.

This stage is not required when the target page of the switch has been loaded.

# 1.6 Page switching animation

After the page is rendered, the client animates a page switch (e.g. pushing the page from right to left). If the page takes longer than a fixed time to initialize and render, the page is pushed forward to avoid the user thinking the page is unresponsive.

The time the page push animation is completed, corresponding to the PerformanceEntry(Route) The end time.

# 2. How to Optimize Page Switching

# 2.1 Avoid in the onHide/onUnload Perform time-consuming operations

When a page switches, the previous page's onHide or onUnload Life cycle before new pages are created and rendered. if onHide and onUnload Execution for too long may cause delays in page switching.

  • onHide/onUnload The logic in should be as simple as possible, if you have to carry out some complex logic, you can consider using setTimeout Delayed.
  • Reduce or avoid the risk of onHide/onUnload Time-consuming logic, such as synchronous interface calls, setData Etc.

# 2.2 First Screen Rendering Optimization

The rendering of the first screen of the page is an important part of the time-consuming page switching, and the optimization method can refer to the start-up performance optimization.First Screen Rendering OptimizationPart.

# 2.3 Initiate data requests in advance

In some scenarios with high performance requirements, when using JSAPI When making a page jump (for example wx.navigateTo), can do some preparation in advance for the next page. Between pages can be accessed by [EventChannel]((api/Page#Interpage communication)) To communicate.

For example, when a page jumps, a data request for the next page can be initiated at the same time, without waiting until the page onLoad This allows users to see the page content earlier. Especially when jumping to the sub-packageing page, from the originating page to the page onLoad There may be longer time intervals between them that can be exploited.

# 2.4 Control when to preload the next page

Base library 2.15.0 Start supporting, Android only. The low version configuration does not take effect.

Such as 1.3 Section, after the Mini Program page loads, the next page is preloaded. By default, the Mini Program framework will appear on the current page onReady trigger 200ms After triggering preload.

On Android, the Mini Program renders all pages of the WebView Share the same thread. In many cases, the initial data of the Mini Program only includes the general frame of the page, and is not the complete content. The main body of the page needs to rely on setData For updates. As a result, preloading the next page may block rendering of the current page, causing setData There is a delay in interaction with the user, affecting the time when the user sees the full content of the page.

To allow users to see the full page content earlier and avoid the impact of the preload process on the page load process, developers can configure handleWebviewPreload Option to control when the next page is preloaded.

handleWebviewPreload There are the following values

  • static: The default value. On the current page onReady trigger 200ms After triggering preload.
  • auto: Preload when the rendering thread is idle. By the base library based on a period of time requestAnimationFrame The trigger frequency algorithm to judge.
  • manual: By the developer by calling the wx.preloadWebview Trigger. Developers can find the main content of the page setData Manually triggered when it's over.

For example:

in app.json In (acting on global control)

{
  "window": {
    "handleWebviewPreload":  "auto"
  }
}

Or on the page JSON File (only works on a single page)

{
  "handleWebviewPreload":  "manual"
}
Page({
  onLoad() {
    this.setData({
      fullData: {}
    }, () => {
      // Only configured to manual When you need to call
      wx.preloadWebview?.()
    })
  }
})

As shown in the figure below, suppose that the complete content of a Mini Program home page is divided into three setData Conducted: