The development and principle of wechat small program

1. The difference between applets and ordinary web development

  • The main development language of small program is JavaScript, and the development of small program is very similar to the common web development. Moving from web development to applets is not expensive for front-end developers, but there are a few differences.

  • The web development rendering thread and script thread are mutually exclusive, which is why long script runs can cause the page to become unresponsive, whereas in applets the two are kept separate and run on separate threads. Web developers can use the DOM API exposed by various browsers for DOM selection and manipulation. As mentioned above, the logic layer of the applet is separate from the render layer. The logic layer runs in JSCore and does not have a full browser object, so it lacks the DOM API and BOM API. This difference results in some libraries familiar to front-end development, such as jQuery, Zepto, etc., not running in small programs. The JSCore environment is also different from the NodeJS environment, so some NPM packages will not run in applets.

  • Web developers need to face a variety of browsers, IE, Chrome, QQ browsers on the PC side, Safari, Chrome and various WebViews in iOS and Android system on the mobile side. In the process of small program development, we need to face the wechat client of the two major operating systems iOS and Android, as well as the small program developer tools for auxiliary development. The three running environments in the small program are also different

2. JSON syntax in applets

Applets in the JSON configuration of some considerations.

JSON files are wrapped in curly braces {} to express data in key-value format. JSON keys must be wrapped in double quotation marks. In practice, it is a common mistake to forget to put double quotation marks around Key values or to write double quotation marks as single quotation marks when writing JSON.

JSON values can be in only one of the following data formats. Any other format will trigger an error, such as undefined in JavaScript.

  • Numbers, including floating-point and integer numbers
  • String, which needs to be enclosed in double quotation marks
  • Bool值,true 或者 false
  • Array, needs to be wrapped in square brackets []
  • Object that needs to be wrapped in braces {}
  • Null

Also note that annotations cannot be used in JSON files, and attempts to add annotations will raise an error.

3. Run time of applets

Render layer and logic layer

The running environment of small programs is divided into the rendering layer and the logical layer, in which WXML templates and WXSS styles work in the rendering layer, and JS scripts work in the logical layer.

The rendering layer and logic layer of the applet are managed by two threads respectively: the interface of the rendering layer uses WebView to render, and the logic layer uses JsCore thread to run JS script. A small program has multiple interfaces, so there are multiple WebView threads in the rendering layer. The communication of the two threads will be transferred through the wechat client, and the network requests sent by the logic layer will also be forwarded through the wechat client.

Logical layer App Service

The logic layer of the small program development framework uses JavaScript engine to provide the running environment of the developer’s JavaScript code and the special functions of wechat small program for the small program.

The logical layer processes the data and sends it to the view layer and receives event feedback from the view layer.

All code written by the developer will eventually be packaged into a JavaScript file and run when the applet is started until it is destroyed. This behavior is similar to a ServiceWorker, so the logical layer is also called an App Service

4. Running mechanism of small program

In the foreground/background state, the interface is displayed to the user after the small program is started. At this time, the small program is in the foreground state. When the user clicks the capsule button in the upper right corner to close the small program, or presses the Home button of the device to leave wechat, the small program does not stop running completely, but enters the background state. The mini program can also run for a short period of time. When the user enters wechat again or opens the mini program again, the mini program will enter the foreground from the background. However, if the user has not entered the applet for a long time, or the system resources are tight, the applet may be destroyed, that is, completely terminated.

Small program start can be divided into two cases: one is cold start, one is hot start.

  • Cold start: If the user opens it for the first time or the user opens it again after the small program is destroyed, the small program needs to be reloaded and started, that is, cold start.
  • Hot start: If the user has opened a small program, and then opens the small program again within a certain period of time, the small program is not destroyed, but from the background state to the foreground state, this process is hot start.

Small program destruction time:

Generally, small programs are destroyed only when they have been in the background for a certain amount of time, or when system resources are too high. Specifically, it includes the following situations:

  • When the applet enters the background, it will maintain the running state for a short period of time. If it does not enter the foreground within this period of time, the applet will be destroyed.
  • When small programs occupy too much system resources, they may be destroyed by the system or recycled by the wechat client.
    • On iOS, when the wechat client receives two or more system memory alarms within a certain period of time (currently 5 seconds), it automatically destroys the small program and prompts the userThis small program may cause slow response of wechat and be terminated
    • It is recommended that applets use wx.onMemoryWarning to listen for memory alarm events and clean up memory if necessary.

Exit status

The page callback function onSaveExitState is called whenever the applets may be destroyed. If you want to preserve the state in the page, you can “save” some data in this callback function, which can be retrieved through exitState at next startup.

5. Development of small programs

On the basis of JavaScript, we have added some features to facilitate the development of applets:

  • Add App and Page methods for program registration and Page registration.
  • Add getApp and getCurrentPages methods to get the App instance and the current page stack, respectively. – – Provide rich API, such as wechat user data, scan, payment and other wechat unique capabilities. Provides modularity, with each page having its own scope.

Note: The logic layer of the applets framework does not run in the browser, so JavaScript cannot be used in web capabilities such as Window, document, etc.

app.js

Before opening the mini program, the wechat client will download the code package of the entire mini program to the local. The pages field of app.json then shows you all the page paths of your current applet.

The first page written in the Pages field in app.json is the home page of the applet

So the wechat client will load in the code of the home page, through some mechanisms at the bottom of the small program, you can render the page

After the applet is launched, the onLaunch callback of the app instance defined in app.js will be executed. The entire applet has only one app instance, which is shared by all pages

var api = require('./utils/request.js').default
App({
  onLaunch: function () {},
  onShow() {},
  onHide() {},
  onError(msg) {console.log(msg)},
  globalData: 'I am global data'
})
Copy the code

You can get a globally unique example App using the getApp method, get data on the App, or call functions that the developer has registered with the App.

const appInstance = getApp()
this.setData({
  globalData: appInstance.globalData
})

<view>
  {{globalData}}  // I am global data
</view>
Copy the code
Page

Applets contain different types of files:

  • Json Configuration file with the suffix. Json
  • WXML template file with the.wxml suffix
  • WXSS suffix WXSS style file
  • Js script logic file with the.js suffix

In a JS file, Page is a Page constructor that generates a Page. When the page is generated, the applet framework renders the data and index. WXML together to render the final structure, and you get what the applet looks like.

After rendering the interface, the page instance receives an onLoad callback where the corresponding logic can be processed.

Page({data: {text: "This is Page data."}, onLoad: function(options) {// Page creation}, onShow: Function () {// when the page appears in foreground}, onReady: function() {// when the page is rendered for the first time}, onHide: function() {// when the page changes from foreground to background}, onUnload: Function () {// execute when the page is destroyed}, onPullDownRefresh: function() {// execute when the pull-down refresh is triggered}, onReachBottom: OnPageScroll: function() {onPageScroll: function() {onPageScroll: Function () {// when the page is scrolling}, onResize: Function () {// when the page size changes}, OnTabItemTap (item) {console.log(item.index) console.log(item.pagepath) console.log(item.text)}, ViewTap: function() {this.setdata ({text: 'Setting some data for updating view.'}, function() {// This is setData callback})}, // customData: {hi: updating view. 'MINA' } })Copy the code

At the heart of the framework is a responsive data binding system that makes it very easy to synchronize data with views. When data is modified, you only need to modify the data in the logical layer, and the view layer will be updated accordingly.

<view> Hello {{name}} </view> <button bindtap="changeName">click me! </button> data: { name: 'xiaowang' }, changeName: function (e) { this.setData({ name: 'Jerry' }) },Copy the code
component

Applets provide a rich set of basic components that developers can assemble into their own routines like building blocks.

For example, if you want to display a map on the interface, you just write the name of the component tag in WXML.

<map></map>
Copy the code

For example, if you want the map to start out with a longitude and latitude of Guangzhou, you need to declare the map’s longitude and latitude:

<map longitude=" longitude "latitude=" latitude "></map>Copy the code
api

In order to enable developers to easily adjust the capabilities provided by wechat, such as access to user information, wechat payment and so on, the small program provides many apis for developers to use. Note that most API callbacks are asynchronous and need to be handled asynchronously with code logic. For example,

Custom Components

Developers can abstract functional modules within a page into custom components that can be reused across different pages, or they can split complex pages into multiple low-coupling modules to facilitate code maintenance.

Custom components are very similar to the base components when used. Develop a custom component, similar to a page, a custom component consists of JSON, WXML, WXSS, JS 4 files:

// json file {" Component ": true // set to custom component}Copy the code

In the js file of a custom Component, you use Component() to register the Component and provide its property definitions, internal data, and custom methods. Component property values and internal data will be used for component WXML rendering, where property values can be passed in from outside the component.

Component({properties: {// The innerText property is defined here. The value of the innerText property can be specified when the Component is used. 'default value',}}, data: {someData: {}, methods: { function () {} }, } })Copy the code

Use custom components

Before using a registered custom component, you must first declare a reference in the JSON file of the page. In this case, you need to provide the label name of each user-defined component and the corresponding path of the user-defined component file:

{"component-tag-name": {"component-tag-name": ".. /.. / components/HelloWorld/index "}} / / use the foot that defines the page component WXML file < component - tag - name / >Copy the code

6. Common setData operation errors

1. Frequent setData visits

Frequent (millisecond) setData removal results in:

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, the user operation event cannot be transferred to the logic layer in time, and the logic layer cannot transfer the operation processing result to the view layer in time, rendering has a delay. As the JS thread of WebView is always in a busy state, the communication time from the logic layer to the page layer increases, and the data message received by the view layer has passed hundreds of milliseconds before it is sent, so the rendering result is not real-time

Each time setData passes a lot of new data

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, it will increase the compilation and execution time of the script and occupy the WebView JS thread.

Background page for setData

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 perceived by the user, and the background state page to setData will also preempt the execution of the front page.

7, the subcontract

In some cases, the developer needs to divide the applets into different subpackages, which are packaged into different subpackages at build time and loaded by users as needed.

When building a applets subcontract project, the build outputs one or more subcontracts. Each subcontracting applet must contain a main package. The main package, where the default launch page /TabBar page is placed, and some common resource /JS scripts are required for all subpackages, which are divided according to the developer’s configuration. When the small program starts, the main package will be downloaded and the page in the main package will be started by default. When the user enters a page in the subpackage, the client will download the corresponding subpackage and display it after downloading.

Currently, the subcontracting size of small program has the following limitations:

  • The subcontracting size of the whole small program does not exceed 8M
  • The size of a single subcontract/main package cannot exceed 2M