preface

All things are difficult before they are easy. Here’s a picture to show your sincerity.

The figure is the overall architecture of wechat small program, detailed analysis will be in the overall architecture of the following, mainly let you have a little impression in your mind, let’s start this happy journey. (= ^ del ^ =)

The development of origin

Let’s first briefly talk about the development of wechat small program, know yourself and know the enemy can not be dangerous in a hundred battles. Wechat small program short for small program. Zhang Xiaolong announced his official launch on Wechat open Class on January 9, 2017. Mini Program is a kind of application that can be used without downloading and installing. It realizes the dream of application “at your fingertips”. Users can open the application by scanning or searching it.

Since the launch of small programs, has been known as the portable version of the APP, the difference between the two is nothing more than small programs are relatively light, low development cost, short development cycle, quick results.

Applets are not a concept that came out of nowhere. When WebView in wechat gradually becomes an important entry point of mobile Web, wechat has JS API.

WebView is a JavaScript running environment provided by mobile terminal (mobile phone, IPad). It is a control for system rendering Web pages. It can interact with page JavaScript to realize the mixed development of APP and Web. WebView rendering of Web pages requires strong rendering kernel support, which is different between Android and IOS kernel.

According to understand, small application background of the birth of the main driving force is due to the mobile web in WeChat spread bad experience, ability is not strong, of course, I think there is a native APP promote the cause of shortcomings, such as every time to download from the APP Store or other application market, even if downloaded, also occupy the space of system greatly, if you don’t often use, The possibility of being deleted by the user is also very high.

Let’s first put aside the problem of native APP. As for the problem of poor experience and weak ability of mobile web pages to spread in wechat, even though the wechat team later launched JS-SDK to solve the problem of insufficient ability of mobile web pages, the JS-SDK mode did not solve the problem of poor experience when using mobile web pages. The reasons for this can be summed up in three points: the white screen problem, the rigidity of page switching and the lag of clicking.

In order to solve these problems, the wechat team faces the problem of how to design a better system, so that all developers can get a better experience in wechat. This problem is not handled by the previous JS-SDK, and requires a new system that enables all developers to do it:

  • Fast loading.
  • Greater ability.
  • Native experience.
  • Easy to use and secure wechat data opening.
  • Efficient and simple development.

That’s where applets come in. The document

The host environment

The host environment of the small program is the wechat client, which is dependent on the wechat client to run, and has a significant relationship with the basic library version of the small program.

We can refer to the micro channel client and small program base library as the host environment of micro channel small program.

Wechat applet can call the ability of the wechat client provided by the host environment, and can complete many functions that ordinary web pages cannot complete, which makes the applet have more capabilities than ordinary web pages. Small programs will run in different versions (different wechat clients + different basic libraries) of the host environment, so it is inevitable to do program compatibility for each version of the host environment.

The execution environment

The main development language of applets is Javascript, which is similar to traditional web development but still has some differences:

  • Web development, rendering threads and scripts are mutually exclusive, which is why long script runs can cause pages to become unresponsive, essentially what we sayJSIt’s single-threaded.
  • Small program, view layer and logic layer are separate, dual program run at the same time, view layer interface useWebViewTo render, the logic layer runs inJSCoreIn the.
  • Web development, which is mainly for browsers of various manufacturers, also needs to be faced on mobileSafari,ChromeAs well asiOS,AndroidVarious types in the systemWebView.
  • Small programs, mainly facing the two major operating systems IOS and Android wechat client, as well as development tools, PC (Window), Mac. The development needs to pay attention to the version number of wechat client and the version number of the basic library supported by the API.

Wechat applets run on a variety of platforms: iOS (iPhone/iPad) wechat client, Android wechat client, PC wechat client, Mac wechat client and wechat developer tools for debugging.

The script execution environment and the environment used to render non-native components vary from platform to platform, as follows:

Runtime environment Logic layer Rendering layer
Android V8 Self-developed Xweb engine, based on Mobile Chrome
IOS JSCore WKWebView
The development tools NW.js Chromium Webview
PC (Window) Chrome kernel Chrome kernel
Mac JSCore WKWebView

I don’t know if you have any questions when you see here. (T_T) uh…… I have some questions about the above sentence, that is, “logic layer runs in JSCore”. The specific idea is explained in the following JSCore directory, which can be viewed below.

Applets overall architecture

Through the above content, you should generally understand the birth of small program and the environment, let’s talk about the overall design framework of small program.

The whole applets system architecture is divided into two parts: the WebView layer (WebView) and the logic layer (App Service), which are managed by two independent threads.

  • View layer: Also known as the render layer, the render layer is used to render the page structure, mainly byWebViewFor rendering, a small program can have more than one interface, so there may be more than one rendering layerWebViewThreads.
  • Logical layer: The logical layer usesJSCoreThe thread runningJSThe script. The logic layer is mainly used for logical processing, data requests, interface calls, etc.

The communication between the view layer and the logical layer needs to communicate with the system layer (WeixinJsBridage). The logical layer notifies the view layer of data changes, triggers page updates of the view layer, and the view layer notifies the triggered events to the logical layer for business logic processing.

The general process of page rendering is as follows: When we compile the project, we will convert WXML into the corresponding JS object (Virtual DOM). When the data changes in the logical layer, we will pass the data from the logical layer to the view layer through setData() method. The view layer will conduct internal comparison after receiving the data. Apply the differences in the original Dom tree, and then correctly render out the UI interface to complete the page rendering process.

From the above analysis, can you understand the architecture diagram placed at the beginning? (a. ^ – ^ -)

The above analysis also mentions a system layer (WeixinJsBridage), commonly referred to as JSBridge, which acts as an intermediate bridge and is very important. It not only makes the view layer and the logic layer two separate threads can communicate, but also sets up a bridge between the upper development and the system’s bottom function (Native), so that small programs can use the Native function by calling API, and some components are realized by the Native component, so as to have a good experience.

The logical layer also has an important operation, sending network requests, which are also forwarded through the system layer.

At this point, I hope you have a certain understanding of the overall structure of the small program, let’s start to talk about the internal mechanism of the small program.

Operation mechanism

There are two situations when small programs start and run:

  • Cold start (restart) : the user opens it for the first time or opens it again after the mini program is actively destroyed by wechat. In this case, the mini program needs to be reloaded and started, that is, cold start.
  • Hot start: The user has opened the small program, and then opens the small program again within a certain period of time. At this time, there is no need to restart the small program, but only need to switch the background state to the foreground. This process is hot start.

Note: 1. Small programs do not have the concept of restart. 2. When the small program enters the background, the client will maintain the running state for a period of time. After a certain period of time, it will be actively destroyed by wechat. 3. After receiving more than two memory warnings from the system in a short period of time, small programs will be destroyed, which is why once the page memory overflow, the page will crash.

Update mechanism

If a new version of a small program is found during cold startup, it asynchronously downloads the package of the new version and starts the program with the old package on the local client first. The program will be applied after the next cold startup. If you need to apply the latest version immediately, you can use the Wx.getupDatemanager API to do so.

Const updateManager = wx. GetUpdateManager () updateManager. OnCheckForUpdate (function (res) {/ / callback request through the new version information The console. The log (res) hasUpdate)}) updateManager. OnUpdateReady (function () {wx. ShowModal ({title: 'updates, content: 'The new version is ready. Do you want to restart the application? ', success(res) {if (res.confirm) {// The new version has been downloaded, Call applyUpdate use new version and restart updateManager. ApplyUpdate ()}}})}) updateManager. OnUpdateFailed (function () {/ / download the new version failed})Copy the code

Data communication mechanism

We mentioned earlier that applets are two-threaded, which means that any data passing between the view layer and the logical layer is communication between threads, which means there is some latency. Unlike the traditional Web, where pages are rendered synchronously when they are updated by calling the relevant API, in applets this is done asynchronously.

Asynchrony complicates the timing of the parts. For example, when rendering the first screen, the logical layer and the rendering layer will start the initialization work at the same time, but the rendering layer needs the data of the logical layer to render the interface. If the initialization work of the rendering layer is completed quickly, the next work can be carried out only after the instruction of the logical layer. Therefore, the logic layer and the rendering layer need to have a certain mechanism to ensure that the timing is correct. In the life cycle of each applet page, there are several times of page data communication.

Now that we know how the view layer communicates with the logic layer, we know a little bit about how the data transfer between the view layer and the logic layer works, and we know that the communication between the view layer and the logic layer is enabled by the system layer, which is actually implemented through evaluateJavascript provided on both sides. That is, the data transmitted by the user needs to be converted into a string for transmission. At the same time, the converted data content is spliced into a JS script, and then transmitted to the independent environment on both sides by executing the JS script.

EvaluateJavascript: Native calls to JS are usually direct JS code strings, similar to how we call eval in JS to execute a string of code. It generally has several methods such as loadUrl and evaluateJavascript. I won’t go into too much detail here, just remember that it is used to call and execute JS strings, which is a Native way of identifying JS code.

Login mechanism

If you’ve ever done a mini program, you’ll be familiar with this:

The process shown in the figure is mainly to obtain the unique OpenID and session_key of wechat users. After that, the developer server can generate a custom login state according to the user id, which is used to identify the user identity during the interaction between the front and back end of the subsequent business logic.

  1. callwx.login()Obtain temporary login credentialscodeAnd back to the developer server.
  2. callauth.code2SessionInterface in exchange for a unique user idopenid, the unique identifier of the user under the wechat open platform accountUnionID(if the current applets have been bound to wechat open platform account) and session keysession_key.

UnionID Mechanism description

UnionID is a newly added property of wechat not long ago. Its acquisition method is similar to OpenID and its function is similar. It refers to the unique identity of the user, but its scope is a little wider.

Official explanation: if the developer has multiple mobile applications, website applications, and public accounts (including small programs), can distinguish the uniqueness of the user through UnionID, because as long as it is the same wechat open platform account under the mobile application, website applications and public accounts (including small programs), the user’s UnionID is unique. In other words, the same user, different applications under the same wechat open platform, UnionID is the same.

Don’t understand? To put it plainly, after binding the small program to the wechat open platform account, it can get through with other mobile applications, website applications and public accounts bound under the account. For example: the same user in the PC scanning login, wechat public account development page authorized login, wechat small program authorized login, these scenarios can be identified as the same user, the UnionID obtained is the same. portal

Performance issues

After learning the architecture principles of applets, we will briefly analyze how common applets performance problems arise from the perspective of the underlying architecture.

Call setData() frequently

Frequently call setData(), this problem is believed to have been very common, such as call in the timer, call in the hook listening to the page scroll, these scenarios can easily cause performance problems of small programs, prone to page lag, page data update is not timely.

In the previous data communication mechanism, we mentioned that applets are based on dual threads, which means that any data transfer between the view layer and the logical layer is communication between threads. Frequent calls to setData() will keep threads busy, and the time of notification from the logical layer to the view layer will increase. The view layer may receive the message after a certain amount of time, rendering the page is not timely enough.

Huge amount of data to call setData()

In the previous data communication mechanism, we said that the transmitted data needs to be converted to the form of string transmission, and executed in the form of JS script. When there is a large amount of data, the compilation and execution time of the script will also increase, occupying threads.

The complex DOM structure of the page

When a page DOM complex structure and a lot of time, this will surely bring page shows not timely, page caton, even may appear page collapses, the reason is that it is conceivable that are drawn too DOM, calculation is need time, this will make the thread transition work, bring the client memory footprint, This triggers the system recycling applet page.

JSCore

I mentioned above that I have some questions about the sentence “logic layer runs in JSCore”, because I saw in the table that the environment of logic layer running should be differentiated according to the system environment. Is this sentence too general? Or is this a reference to IOS? Since it was written in an official document, I did not directly reject it as a mistake, or as a single reference to IOS.

After checking, it turns out that there is no problem with this statement. To trace the result, we need to write the general condition of the browser:

The core part of the browser is the browser kernel, each browser has its own kernel, and the biggest impact on the mobile world is WebKit.

WebKit is a page rendering and logic processing engine that processes HTML/CSS/JavaScript to become visible and actionable Web pages.

WebKit consists of a number of important modules, the overall structure is shown as follows:

WebKit consists of four parts:

  • WebKit Embedding API: Is responsible for the interaction between the browser UI and WebKit.
  • Platform API (WebKit Ports):WebkitIt is more convenient to transplant to various operating systems and platforms, and provides some interfaces to call Native Library.
  • WebCore: the wholeWebKitAt the heart of the rendering engine.
  • JavascriptCore:JSCoreWebKitDefault embedded JS engine, used by AppleCDevelopment.

Let’s focus on JSCore. JSCore is the default javascript engine built into WebKit. It’s the default javascript engine built into WebKit because many browser engines based on WebKit have developed their own JS engine, the most famous of which is Chrome’s V8 engine.

V8 engine, believe the front-end partners should not be very strange, since it is based on WebKit, the underlying default is embedded JSCore, and Android logic layer is running on V8.

The browser engine for IOS is WebKit, and inside it is JSCore.

Finally, the logic layer of the development tool is run on nw.js.

I believe it has something to do with WebKit as well.

To this problem there is a certain understanding, xiaobian did not continue to go deep, end it. (a. ^ – ^ -)

At this point, this article is finished, sa Hua Sa hua.

I hope this article has been helpful to you. If you have any questions, I am looking forward to your comments. Same old, likes + comments = you know it, favorites = you know it.