Detailed explanation of the basic principles of WeChat mini program architecture

WBOY
Release: 2022-10-11 14:13:13
forward
5562 people have browsed it

This article brings you related issues about WeChat Mini Program, which mainly introduces the relevant content about the basic architecture principles, including the host environment, execution environment, and the overall structure of the mini program , operating mechanism, update mechanism, data communication mechanism, etc. Let’s take a look at them together. I hope it will be helpful to everyone.

Detailed explanation of the basic principles of WeChat mini program architecture

[Related learning recommendations: Mini Program Learning Tutorial]

The following picture shows the overall architecture of the WeChat Mini Program:

Detailed explanation of the basic principles of WeChat mini program architecture

Origin of Development

Let’s first briefly talk about the development history of WeChat Mini Programs. Only by knowing ourselves and the enemy can we win every battle. WeChat mini program is referred to as mini program. Zhang Xiaolong announced its official launch in the WeChat open class on January 9, 2017. The English name of mini program is Mini Program. It is an application that does not require downloading and installation. It realizes the dream of having applications "at your fingertips". Users can open applications by scanning or searching.

Since the mini program was launched, it has been called the portable version of the APP. The difference between the two is that the mini program is relatively lightweight, has low development cost, short development cycle, and quick results.

Mini programs are not a concept that emerged out of thin air. When WebView in WeChat gradually became an important entrance to the mobile Web, WeChat had related JS APIs.

WebView is an environment for running JavaScript provided by mobile terminals (mobile phones, IPads). It is a control for the system to render Web pages. It can interact with JavaScript on the page to achieve mixed development of APP and Web. WebView rendering Web pages require powerful rendering kernel support, and the kernels of Android and IOS systems are different.

According to my understanding, the main driving force behind the birth of mini programs is the poor communication experience and weak ability of mobile web pages in WeChat. Of course, I think this is also driven by the shortcomings of native APPs, such as the disadvantages of each You have to download it from the App Store or other application markets every time. Even if you download it, it takes up a lot of space in the system. If you don't use it often, the possibility of being deleted by the user is very high.

Let’s put aside the issue of native APP. As for the problem of poor communication experience and weak ability of mobile webpages in WeChat, even though the WeChat team later launched JS-SDK to solve the problem of insufficient mobile webpage capabilities. , but the JS-SDK model does not solve the problem of poor experience when using mobile web pages. The reasons can be summarized into these three points: white screen problem, stiff page switching and lag in clicks.

In order to solve these problems, the problem faced by the WeChat team is how to design a better system so that all developers can get a better experience in WeChat. This problem cannot be handled by the previous JS-SDK and requires a brand new system to complete it. It needs to enable all developers to achieve:

  • Fast loading.

  • More powerful abilities.

  • Native experience.

  • Easy-to-use and secure WeChat data openness.

  • Efficient and simple development.

This is the origin of mini programs. Document

Host environment

The hosting environment of the WeChat applet is the WeChat client. It depends on running on the WeChat client and has a significant relationship with the version of the basic library of the applet.

We can refer to WeChat client and Mini Program basic library as the hosting environment of WeChat Mini Program.

WeChat mini programs can call the capabilities of the WeChat client provided by the host environment and can complete many functions that ordinary web pages cannot complete. This makes mini programs have more capabilities than ordinary web pages. Mini programs will run in host environments of different versions (different WeChat clients and different basic libraries), so it is inevitable to make programs compatible with each version of the host environment.

Execution environment

The main development language of small programs is Javascript, which is similar to traditional web development but still has certain differences:

  • Web page development, rendering threads and scripts are mutually exclusive, which is why long-term script running may cause the page to lose response. The essence is that we often say that JS is single-threaded.

  • In the mini program, the view layer and the logic layer are separated, and two threads run at the same time. The interface of the view layer is rendered using WebView, and the logic layer runs in JSCore.

  • Web development mainly deals with browsers from various manufacturers. On the mobile side, it also needs to deal with various WebViews in Safari, Chrome, iOS, and Android systems.

  • Mini programs are mainly used for WeChat clients of the two major operating systems IOS and Android, as well as development tools, PC (window), and Mac. When developing, you need to pay attention to the version number of the WeChat client and the version number of the basic library supported by the mini program API.

WeChat applet runs on multiple platforms: iOS (iPhone/iPad) WeChat client, Android WeChat client, PC WeChat client, Mac WeChat client and WeChat development for debugging tool.

The script execution environment of each platform and the environment used to render non-native components are different. The specific differences are as follows:

Detailed explanation of the basic principles of WeChat mini program architecture

Overall structure of the mini program

Through the above content, you should have a general understanding of the birth and environment of the mini program. Now let’s talk about the overall design structure of the mini program.

The entire mini program system architecture is divided into two parts: the view layer (WebView) and the logic layer (App Service). These two parts are managed by two independent threads.

  • View layer: Also called the rendering layer, the rendering layer is used to render the page structure, mainly rendered by WebView. A small program can have multiple interfaces, so there may be multiple rendering layers. WebView thread.

  • Logical layer: The logic layer uses JSCore threads to run JS scripts. The logic layer is mainly used for logic processing, data requests, interface calls, etc.

The communication between the view layer and the logic layer requires the use of the system layer (WeixinJsBridage). The logic layer notifies the view layer of data changes and triggers the view layer page update. The view layer Notify the triggered events to the logic layer for business logic processing.

The general process of page rendering is: 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 use the setData() method Pass the data from the logic layer to the view layer. After receiving the data, the view layer will compare the differences internally, apply the differences to the original Dom tree, and then correctly render the UI interface to complete the page rendering process.

Through the above analysis, can you understand the architecture diagram placed at the beginning?

The above analysis also mentions a system layer (WeixinJsBridage), generally referred to as JSBridge, which It plays the role of a middle bridge, which is very important. It not only allows two separate threads of the view layer and the logic layer to communicate, but also builds a bridge between upper-level development and the underlying system functions (Native), allowing small programs to use native functions by calling APIs, and some components are implemented with native components. , thereby having a good experience.

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

Having said this, I hope you have a certain understanding of the overall structure of the mini program. Let’s start by talking about some of the internal mechanisms of the mini program.

Operating mechanism

There are two situations when the mini program starts and runs:

  • Cold start (restart): The user opens the mini program for the first time or the mini program is actively activated by WeChat When it is opened again after being destroyed, the applet needs to be reloaded and started, which is a cold start.

  • Hot start: The user has already opened the applet, and then opens it again within a certain period of time. There is no need to restart at this time, and only needs to switch the applet in the background to the foreground. , this process is hot start.

Note:

1. Mini programs do not have the concept of restarting.

2. When the mini program enters the background, the client will maintain a running state for a period of time, and will be actively destroyed by WeChat after a certain period of time.

3. If the system receives more than two memory warnings in a short period of time, the applet will be destroyed. This is the essential reason why the page will crash once the page memory overflows.

Update mechanism

If a new version is found during the cold start of the mini program, the new version of the package will be downloaded asynchronously, and at the same time it will be started with the old local package of the client first, wait a moment It will be applied only after a cold start. If you need to apply the latest version immediately, you can use the wx.getUpdateManager API to handle it.

const updateManager = wx.getUpdateManager()
updateManager.onCheckForUpdate(function (res) {
  // 请求完新版本信息的回调
  console.log(res.hasUpdate)
})
updateManager.onUpdateReady(function () {
  wx.showModal({
    title: '更新提示',
    content: '新版本已经准备好,是否重启应用?',
    success(res) {
      if (res.confirm) {
        // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
        updateManager.applyUpdate()
      }
    }
  })
})
updateManager.onUpdateFailed(function () {
  // 新版本下载失败
})
Copy after login

Data communication mechanism

We mentioned earlier that the applet is based on dual threads, which means any data transfer between the view layer and the logic layer It's all communication between threads, which means there will be a certain delay. This is not like the traditional Web, where when the page needs to be updated, it can be rendered synchronously by calling the relevant API. In the mini program architecture, all this is an asynchronous operation.

Asynchronous will make the running timing of each part more complicated. For example, when rendering the first screen, the logic layer and the rendering layer will start initialization work at the same time, but the rendering layer needs data from the logic layer to render the interface. If the rendering layer initialization work is completed quickly, you have to wait for instructions from the logic layer. Only then can we proceed to the next step. Therefore, the logic layer and rendering layer need a certain mechanism to ensure correct timing. During the life cycle of each mini program page, there are several page data communications.

Detailed explanation of the basic principles of WeChat mini program architecture

After knowing the specific communication process between the view layer and the logic layer, we also have a little understanding of the data transmission between the view layer and the logic layer. We know that the communication between the two relies on the function of the system layer, but in fact It is implemented through evaluateJavascript provided by both sides. That is, the data transmitted by the user needs to be converted into a string and passed on. At the same time, the converted data content is spliced ​​into a JS script, and then passed to the independent environments on both sides by executing the JS script.

About evaluateJavascript:

Native calls JS, usually a direct JS code string, which is somewhat 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 introduction here. You just need to remember that it is used to call and execute JS strings. It is a way for Native to identify JS code.

Login mechanism

Those who have done small programs should be familiar with this picture:

Detailed explanation of the basic principles of WeChat mini program architecture

The main process in the picture is The purpose is to obtain the unique openid and session_key of the WeChat user. Then the developer server can generate a custom login state based on the user ID, which can be used to identify the user's identity during front-end and back-end interactions in subsequent business logic.

  • Call wx.login() to obtain the temporary login credential code and send it back to the developer server.

  • Call the auth.code2Session interface in exchange for the user's unique identifier openid, the user's unique identifier UnionID under the WeChat open platform account (if the current mini program has been bound to the WeChat open platform account) and Session key session_key.

UnionID mechanism description

UnionID is a property newly added by WeChat not long ago. Its acquisition method is similar to openid, and its functions are similar. They all refer to the user's unique identifier. But it's a little broader.

Official explanation: If a developer has multiple mobile applications, website applications, and public accounts (including mini programs), UnionID can be used to distinguish the uniqueness of users, because as long as the same WeChat is open For mobile applications, website applications and public accounts (including mini programs) under the platform account, the user's UnionID is unique. In other words, for the same user, the UnionID is the same for different applications under the same WeChat open platform.

don't know? To put it bluntly, after binding the mini program to a WeChat open platform account, it can be connected with other mobile applications, website applications and public accounts bound to the account. For example: the same user scans and logs in on the PC, authorizes the page developed by WeChat official account, and authorizes the WeChat applet. In these scenarios, it can be identified that the same user is the same, and the obtained UnionID is the same. Portal

Performance issues

After learning the architectural principles of mini programs, let’s briefly analyze how common mini program performance problems arise from the perspective of the underlying architecture.

Frequently calling setData()

Frequently calling setData() is believed to be a very common problem, such as calling it in a timer , called in a hook that monitors page scrolling. These scenarios can easily cause performance problems of the mini program, such as page freezes and untimely page data updates.

We mentioned earlier in the data communication mechanism that the mini program is based on dual threads, which means that any data transfer between the view layer and the logic layer is communication between threads, and frequent calls are made setData() will keep the threads in a busy state, and the logic layer will take longer to notify the view layer. When the view layer receives the message, it may have been more than a certain time since it was sent, and rendering the page will not be timely enough. .

The huge amount of data calls setData()

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

Complex and numerous DOM structures of the page

When a page has a complex and very large DOM structure, this will inevitably lead to delayed page display. , the page is stuck, and the page may even crash. The reason for this can be imagined. It takes time to draw and calculate the DOM, which will make the thread transition work and increase the memory usage of the client. rises, thus triggering the system to recycle the mini program page.

JSCore

I mentioned above that I have some doubts about the sentence "the logic layer runs in JSCore" because I saw that the environment in which the logic layer runs should be listed in the table. They are distinguished according to the system environment. Is this sentence too general? Or does this sentence refer to the situation of iOS? Because it is written in an official document, I did not directly reject it because it was wrongly written, or it only refers to the situation of IOS.

Detailed explanation of the basic principles of WeChat mini program architecture

After some verification, it was confirmed that there is no problem with this sentence. To trace the process of the result, we need to write about the general situation of the browser:

The core part of the browser is the browser kernel. Each browser has its own kernel, and the one that has the most profound impact on the mobile field is WebKit.

WebKit is a page rendering and logic processing engine. HTML/CSS/JavaScript is processed by it and becomes a visible and operable Web page.

WebKit is composed of several important modules. The overall structure is as follows:

Detailed explanation of the basic principles of WeChat mini program architecture

WebKit is composed of four parts, namely:

  • WebKit Embedding API: responsible for the interaction between the browser UI and WebKit.

  • Platform API (WebKit Ports): Makes WebKit more convenient to transplant to various operating systems and platforms, and provides some interfaces for calling Native Library.

  • WebCore: The core rendering engine in the entire WebKit.

  • JavascriptCore: JSCore is the default embedded JS engine of WebKit, developed by Apple using C.

Let’s focus on the JSCore part. JSCore is the default embedded JS engine of WebKit. It is said to be embedded by default because many browser engines developed based on the WebKit branch are Developed its own JS engine, the most famous of which is Chrome's V8 engine.

V8 engine, I believe front-end friends will be familiar with it. Since it is based on WebKit, the bottom layer is also embedded with JSCore by default, and the logic layer of Android runs on V8.

The browser engine of IOS is WebKit, and the internal one is JSCore.

Finally, the logic layer of the development tool runs on NW.js. Go to its official website and see this paragraph:

Detailed explanation of the basic principles of WeChat mini program architecture

I believe it should also It has something to do with WebKit.

[Related learning recommendations: 小program learning tutorial]

The above is the detailed content of Detailed explanation of the basic principles of WeChat mini program architecture. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.im
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!