Writing Background
I have been exposed to small programs for a while. Generally speaking, the threshold for developing small programs is relatively low, but you still need to understand the basic operating mechanisms and principles. "For example, I was asked a question about a mini program during the interview. Does the mini program have a window object? He said yes," but in fact it doesn't. It feels like he doesn't understand some of the underlying things of the mini program. In the final analysis, he can only use this tool, but he doesn't understand the reason.
Mini programs are very different from ordinary web development, which needs to be analyzed from the bottom of its technical architecture. For example, developers who are accustomed to Vue and react development will complain about the cumbersomeness of creating a new page for a mini program. The page must be composed of multiple files, component support is incomplete, and each time the data in the data is changed, setData must be set. It is not as convenient as Vue. Watch monitors and cannot operate Dom, which is not good for complex scenarios. It did not support npm, sass, and less precompiled processing languages before.
"Some people say that mini programs are like castrated Vue", haha. Of course, their starting points for design are different. We also have to understand the original intention of mini program design. Through its usage scenarios, it Why is this technical architecture adopted and what are the benefits of this technical architecture? I believe you will understand it after you understand this. Below I will analyze the operating mechanism of the mini program and its overall technical architecture from the following perspectives.
Understand the origin of mini programs
Before mini programs came out, WeChat WebView gradually became an important entrance to the mobile web. WeChat released a complete set of web development toolkits. Called JS-SDK, it opens a new window for all web developers, allowing all developers to use WeChat's native capabilities to accomplish things that were previously impossible or difficult to do.
However, the JS-SDK model does not solve the problems of poor experience when using mobile web pages, such as the possibility of a white screen due to limited device performance and network speed. Therefore, an enhanced version of JS-SDK was designed, which is "WeChat Web Resource Offline Storage", but the problem of white screen still occurs on complex pages. The reason is the stiffness of page switching and the lag of clicks. At this time, a system that can not be handled by JS-SDK is needed to make the user experience better, and small programs came into being.
Fast loading
More powerful capabilities
Native experience
Easy-to-use and secure WeChat data opening
Efficient and Simple development
The difference between small programs and ordinary web page development
The development of small programs is very similar to the development of ordinary web pages. The main development language is also JavaScript, but there are still some differences between the two.
Ordinary web development can use the DOM API provided by various browsers to perform DOM operations. The logic layer and rendering layer of the applet are separated. The logic layer runs in JSCore and does not have a complete browser object. , thus lacking related DOM API and BOM API.
Ordinary web development rendering threads and script threads are mutually exclusive, which is why long-term script running may cause the page to lose response. In small programs, the two are separated and run on different in the thread.
When web developers develop web pages, they only need to use a browser and use some auxiliary tools or editors. The development of mini programs is different. It needs to go through the process of applying for a mini program account, installing mini program developer tools, configuring projects, etc.
Execution environment of mini program
Structure of mini program
1. Technology selection
General Generally speaking, there are three technologies for rendering interfaces:
Rendering using pure client-side native technology
Rendering using pure Web technology
Using client-side native technology and Web technology Combined hybrid technology (Hybrid technology for short) to render
Through the following aspects analysis, which technical solution is used for the mini program
Development threshold: Web threshold is low, Native also has RN like this Framework supports
Experience: Native experience is much better than Web, Hybrid is closer to native experience than Web to a certain extent
Version update: Web supports online updates, Native needs to be packaged to WeChat for review Release
Control and security: The Web can jump or change page content, and there are some uncontrollable factors and security risks
Since the host environment of the mini program is WeChat, if you use pure client native If you use technology to write mini programs, then the mini program code needs to be released together with the WeChat code every time. This method is definitely not feasible.
So it is necessary to have a resource package that can be updated at any time in the cloud like web technology. It can be downloaded to the local and the interface can be rendered after dynamic execution. If you use pure web technology to render small programs, you may face some performance problems in some complex interactions. This is because in web technology, UI rendering and JavaScript script execution are executed in a single thread, which can easily lead to Some logical tasks seize UI rendering resources.
So we finally adopted the Hybrid technology that combines the two to render the small program. It can be developed in a way similar to the web, and the code can be updated online. At the same time, introducing components also has the following benefits:
Expand the capabilities of the Web. For example, input box components (input, textarea) have the ability to better control the keyboard
The experience is better, and it also reduces the rendering work of WebView
Bypassing setData, data communication and re-rendering Process to make rendering performance better
Using client-side native rendering to build in some complex components can provide better performance
2. Dual-thread model
The rendering layer and logic layer of the applet are managed by two threads respectively: the view layer interface uses WebView for rendering, and the logic layer uses JsCore threads to run JS scripts.
So why is it designed like this? Control and security were also mentioned earlier. In order to solve these problems, we need to prevent developers from using some, such as the browser's window object, jumping pages, operating DOM, and dynamic execution. An open interface for scripting.
We can use the JavaScript engine of the client system, the JavaScriptCore framework under iOS, and the JsCore environment provided by the Tencent x5 kernel under Android.
This sandbox environment only provides a pure JavaScript interpretation and execution environment without any browser-related interfaces.
This is the origin of the dual-thread model of the mini program:
Logic layer: Create a separate thread to execute JavaScript, where all code related to the business logic of the mini program is executed, responsible for the logic Processing, data requests, interface calls, etc.
View layer: All tasks related to interface rendering are executed in the WebView thread, and which interfaces are rendered are controlled through the logic layer code. A small program has multiple interfaces, so there are multiple WebView threads in the view layer.
JSBridge serves as a bridge between upper-level development and Native (system layer), allowing the small program to use native functions through the API, and Some components are implemented as native components, so you have a good experience
3. Dual-thread communication
Put the developer's JS logic code into a separate thread to run, but In the Webview thread, developers cannot directly manipulate the DOM.
How to dynamically change the interface?
As shown in the figure above, the communication between the logical layer and the view layer will be relayed by Native (WeChat client), and network requests sent by the logical layer will also be forwarded by Native.
This means that we can update the DOM through simple data communication.
Virtual DOM I believe everyone already understands it, it is roughly the process: Use JS objects to simulate the DOM tree -> Compare the differences between the two virtual DOM trees -> Apply the differences to the real DOM tree .
As shown in the figure:
Convert WXML into the corresponding JS object in the rendering layer.
When data changes occur in the logical layer, the data is passed from the logical layer to Native through the setData method provided by the host environment, and then forwarded to the rendering layer.
After comparing the differences before and after, apply the differences to the original DOM tree and update the interface.
We realize the interaction and communication between the logic layer and the rendering layer by converting WXML into data and forwarding it through Native.
Such a complete framework cannot be separated from the basic library of the mini program.
4. The basic library of the mini program
The basic library of the mini program can be injected into the view layer and logic layer to run, and is mainly used for the following aspects:
In the view layer, various components are provided to build interface elements
In the logic layer, various APIs are provided to handle various logics
Processing data binding and component systems , event system, communication system and a series of framework logic
Since the rendering layer and logic layer of the applet are managed by two threads, the two threads are each injected with the basic library.
The basic library of the mini program will not be packaged in the code package of a certain mini program, it will be built into the WeChat client in advance.
This can:
Reduce the code package size of the business applet
You can fix the bugs in the basic library separately without modifying the code package of the business applet
5. Exparser Framework
Exparser is the component organization framework of the WeChat applet. It is built into the basic library of the applet and provides basic support for various components of the applet. All components within the mini program, including built-in components and custom components, are organized and managed by Exparser.
The main features of Exparser include the following:
Based on the Shadow DOM model: the model is highly similar to the ShadowDOM of WebComponents, but does not rely on the browser's native support. There are no other dependent libraries; during implementation, other APIs have been specifically added to support small program component programming.
Can run in a pure JS environment: This means that the logic layer also has certain component tree organization capabilities.
Efficient and lightweight: Good performance, especially in environments with a large number of component instances, and the code size is also small.
In the mini program, all node tree-related operations rely on Exparser, including the construction of the final node tree from WXML to the page, createSelectorQuery calling and custom component characteristics, etc.
Built-in components
Based on the Exparser framework, the mini program has a set of built-in components, providing view container classes, form classes, navigation classes, media classes, open classes, etc. Dozens of components. With such a rich set of components, coupled with WXSS, you can build an interface with any effect. At the functional level, it also meets most needs.
6. Operating Mechanism
There will be two situations when the applet is started, one is "cold start" and the other is "hot start". If the user has already opened a small program and then opens it again within a certain period of time, there is no need to restart at this time. Just switch the small program in the background to the foreground. This process is a hot start; a cold start refers to the user's When the mini program is opened for the first time or opened again after being actively destroyed by WeChat, the mini program needs to be reloaded and started.
There is no concept of restarting the mini program
When the mini program enters the background, the client will maintain a running state for a period of time. After a certain period of time (currently 5 minutes) Will be actively destroyed by WeChat
When more than two system memory alarms are received in a short period of time (5s), the mini program will be destroyed
7. Update mechanism
If a new version of the mini program is found during cold start, the new version of the code package will be downloaded asynchronously and started with the client's local package at the same time. That is, the new version of the mini program needs to wait for the next time It will only be applied after a cold start. If you need to apply the latest version immediately, you can use the wx.getUpdateManager API to handle it.
8. Performance Optimization
The main optimization strategies can be summarized into three points:
Streamline the code and reduce the complexity of the WXML structure and JS code ;
Use setData calls reasonably to reduce the number of setData and the amount of data;
Use subcontracting optimization when necessary.
1. How setData works
The view layer of the applet currently uses WebView as the rendering carrier, while the logic layer uses independent JavascriptCore as the running environment. Architecturally, WebView and JavascriptCore are independent modules and do not have channels for direct data sharing. Currently, data transmission between the view layer and the logic layer is actually implemented through the evaluateJavascript provided by both parties. 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.
The execution of evaluateJavascript will be affected by many aspects, and the data arriving at the view layer is not real-time.
2. Common setData operation errors
Frequently setData In some cases we have analyzed, some small programs will setData very frequently (milliseconds) setData, which leads to two consequences: users under Android will feel stuck when sliding, and operation feedback is seriously delayed. Because the JS thread has been compiling and rendering, it fails to pass user operation events to the logic layer in time, and the logic layer also The operation processing results cannot be delivered to the view layer in time; there is a delay in rendering. Since the JS thread of WebView is always busy, the communication time from the logic layer to the page layer increases, and the data message received by the view layer is delayed from the time it is sent. Hundreds of milliseconds have passed, and the rendering results are not real-time;
Every time setData transfers a large amount of new data, it can be seen from the underlying implementation of setData that our data transmission is actually an evaluateJavascript
script process, when the amount of data is too large, it will increase the compilation and execution time of the script, occupy the WebView JS thread, and perform setData on the background state page. When the page enters the background state (invisible to the user), setData should not continue to render the background state page to the user. It is incomprehensible. In addition, settingData on the background page will also preempt the execution of the foreground page.
Summary
This article roughly analyzes the underlying architecture of the mini program from the above perspectives, from the origin of the mini program to the emergence, design, communication, and basics of dual threads. Libraries, Exparser framework, running mechanism, performance optimization, etc. are all related and mutually affecting choices. There should be a lot more about the design of the underlying framework of small programs. The birth of each framework has its own significance. As developers, what we can do is not only use this tool, but also understand its design patterns. Only in this way can you not be influenced by tools and go further!
The above is the detailed content of A brief analysis of the operating mechanism of mini programs. For more information, please follow other related articles on the PHP Chinese website!