当前位置:网站首页>Deep understanding of the underlying framework of wechat applet (I)
Deep understanding of the underlying framework of wechat applet (I)
2022-07-23 13:30:00 【A snail riding a motorcycle】
Everyone is very familiar with small program development . now , We will introduce you all the details behind the coding of small programs , Here we will first go deep into the bottom of the applet , Introduce The underlying architecture design , some Principle of detail , And the familiar component system . Through the study , We can write more reasonable code in the later small program development , There can be evidence to follow when encountering problems , Can think of a better solution .
1 Two thread model
in front , We have mentioned that the applet is based on the dual thread model , In this model , The logic layer and rendering layer of the applet run separately in different threads , It's traditional Web The single threaded model is very different , This makes the small program architecture more complex , There are also some restrictions . As for why we choose to build small programs based on the dual thread model , And the resulting problems and solutions , Next, we will introduce .
1.1 Technology selection
We have only one requirement when designing the architecture of small programs , Just be quick , Including rendering fast 、 Load fast, wait . When the user clicks on a small program , What we expect to experience is a very short loading interface , After a transition animation, you can immediately see the main interface of the applet .
We first need to determine what technology to use to render the applet interface , This is closely related to the learning threshold of developers .
Generally speaking , There are three techniques for rendering interfaces :
- Render with pure client native technology
- In pure Web Technology to render
- Between client native technology and Web Between technologies , Technologies that combine their own characteristics ( Hereinafter collectively referred to as Hybrid technology ) To render
Because the host of the applet is wechat , So we are unlikely to use pure client-side native technology to write small programs . If you do , that Small program code needs to be packaged together with wechat code , Follow the wechat version , This way and the development rhythm must be wrong . therefore , We need to be like Web Technology like that , There is a resource package that can be updated at any time on the cloud , Download to local , After dynamic execution, the interface can be rendered .
however , If we use pure Web Technology to render applets , On some pages with complex interactions, you may face some performance problems , This is because in the Web In technology ,UI Render with JavaScript The script execution of is executed in a single thread , This is easy to lead to some logical task preemption UI Resources for rendering .
As discussed above , Use pure client native technology or pure Web Technology has its own shortcomings , If you use a combination of the two Hybrid Technology to render applets , Can it be better than the technical solutions of independent rendering ? actually , such Hybrid Technology has evolved several technical solutions in the industry in the past few years , Typical, such as early PhoneGap[1], There are also popular in recent two years React Native[2]( Hereinafter referred to as RN), There are also things like those in wechat web pages JS-SDK[3] This lightweight application .
From the bottom layer of rendering ,PhoneGap And wechat JS-SDK It's similar , They all end up using the browser kernel to render the interface . and RN Is different , Although it's for Web Related technology , It also takes advantage of JavaScript Explain the characteristics of execution , but RN At the bottom of the rendering, the client is used for native rendering . actually , When the applet is initially selected RN One of the candidates , Although I say RN It's a combination of React The code composition of the framework , But we can completely separate React The writing method of framework , Define a code composition method that is more in line with the characteristics of small programs . however , In the end, we didn't choose this kind RN technology , There are three reasons. :
- RN The supported styles are CSS Subset , It's not enough Web The growing demand of developers , And yes RN The transformation of has no small cost and risk .
- RN There are still some unstable problems under the existing capacity , Such as performance 、Bug etc. .RN It is to hand over all rendering work to the client for native rendering , In fact, some simple interface elements are used Web Technical rendering is totally up to , And it's very stable .
- RN There are some unexpected factors , For example, the licensing agreement issue has emerged recently .
Final , We choose something similar to wechat JSSDK In this way Hybrid technology , namely The interface is mainly composed of mature Web Technical rendering , Supported by a large number of interfaces to provide rich client-side native capabilities . meanwhile , Each applet page uses a different WebView To render , This can provide a better interactive experience , Closer to the original experience , It also avoids single WebView The task is too heavy . Besides , For interface rendering, we have defined a set of built-in components to unify the experience , And provide some basic and general capabilities , Further reduce the learning threshold of developers . It is worth mentioning that , Some of the more complex components of the built-in components are rendered native to the client , To provide better performance , Later, we will introduce in depth .
1.2 Control and safety
be based on Web Technology to render small programs has some uncontrollable factors and security risks . This is because Web Technology is very open and flexible , We can use JavaScript The script randomly jumps to the web page or changes any content on the interface .
We originally defined a set of built-in components to provide a unified experience , When the user enters the applet , The applet code package will be pulled locally , This allows the applet to browse offline ( As long as the applet developer caches some application data locally ), But if the developer passes JavaScript Render the applet WebView Jump to other online pages , This experience becomes very bad .( Not as good as the local cache experience ..)
besides , We also provide a component that can display sensitive data ( These data can only be displayed , Developers can't get the data ), If developers can pass JavaScript interface (DOM Trees ), So as to directly obtain these sensitive data , That little program is not safe .
In order to solve the problems of control and safety , We must prevent developers from using some browsers , For example, jump to the page 、 operation DOM、 Open interface of dynamic execution script . Suppose we prohibit one by one , It is bound to enter a war of attack and defense , This is because JavaScript Flexibility and richness of browser interface , It's easy to miss some dangerous interfaces , And even if we find all the dangerous interfaces , Maybe the next browser kernel update will add an interface that may cause vulnerabilities under this system , This is still unavoidable .
therefore , To solve this problem thoroughly , We must provide a sandbox environment to run developers JavaScript Code . This sandbox environment cannot have any browser related interfaces , Only pure JavaScript The interpretation of the implementation environment , So it's like HTML5 Medium ServiceWorker、WebWorker Characteristics meet such conditions , Both enable another thread to execute JavaScript. But considering that the applet is more than one WebView The architecture of , We can't use one WebView Medium ServiceWorker To manage all the applet pages . Each applet page is different WebView Displayed after rendering , Under this framework
Thanks to the Client system has JavaScript Our interpretation engine ( stay iOS The following is built-in JavaScriptCore frame , In Android, Tencent x5 kernel-provided JsCore Environmental Science ), I You can create a separate thread to execute JavaScript, In this environment, all the code executed is about the business logic of the applet , That is, the logic layer we have been talking about before . All the tasks related to interface rendering are WebView Execute in thread , Through the logic layer code to control which interface to render , Then this layer is of course the so-called rendering layer . This is the origin of the two thread model of applet .
1.3 Natural delay
Since the applet is based on the dual thread model , That means that any data transmission is the communication between threads , That is, there will be a certain delay . It's not like tradition Web like that , When the interface needs to be updated , Update the interface by calling UI Will be rendered synchronously . In the applet architecture , All this will become asynchronous .
Asynchrony will complicate the running timing of each part . For example, when rendering the first screen , The logical layer and the render layer start initialization at the same time , However, the rendering layer needs the data of the logical layer to render the interface , If render layer initialization is completed faster , We have to wait for the instructions of the logic layer to proceed to the next step . therefore The logic layer and rendering layer need to have a certain mechanism to ensure the correct timing , These tasks will be handled well in the framework of the applet , Developers only need to understand the lifecycle , And control the right time to update UI that will do . More details of the operation process will be introduced later .
In addition to the communication delay between the logic layer and the rendering layer , The native interaction between each layer and the client is also delayed . Take the logic layer as an example , The developer's code runs on the thread of logic layer , The client is native to the main thread of wechat ( Threads on Android ) above , So register to the interface of the logical layer about the client capability , In fact, it is also the communication with the main thread of wechat , It also means there is a delay . This is why we see that most of the provided interfaces are asynchronous .
Because they are all inter thread communication , So the problems caused by delay and asynchrony after the meeting , But these are handled by wechat applet framework , We just need to understand the framework .
After understanding many inherent delays in applet architecture , It will be easier for us to think of solutions to some problems . such as , We are using a canvas (canvas Components ) When doing image processing and exporting photos , Will habitually call draw Method after rendering , Call immediately wx.canvasToTempFilePath Interface to export pictures , In fact, it is likely that the canvas has not finished rendering at the time of calling, so that the exported image is not the desired effect .
Code list Use canvas Export picture script
var ctx = wx.createCanvasContext('myCanvas');
ctx.fillRect(0, 0, 100, 100);
// ……
ctx.draw();
// The following calls should be made in ctx.draw Executed in the callback function called
wx.canvasToTempFilePath({
canvasId: 'myCanvas',
success(res) {
console.log('canvasToTempFilePathresult: ' + res.tempFilePath);
}
});
边栏推荐
- Numpy: element selection of matrix
- Beihui information is 12 years old | happy birthday
- MySQL - composite query external connection
- -XX:+UseCGroupMemoryLimitForHeap 无法创建虚拟机问题
- MetaApp开发面试题目
- Knowledge map: basic concepts
- Day 10 notes
- 倍福PLC和C#通过ADS通信传输int类型变量
- Talk about study and work -- Qian Xuesen
- Complex networks - common drawing software and libraries
猜你喜欢

功能测试转自动化测试,十年自动化测试经验分享

Target segmentation for 10000 frames of video, with less than 1.4GB of video memory | eccv2022

分类模型的评估

Successful joint commissioning of Vientiane Aoke and CoDeSys Technology

The current situation of the industry is disappointing. After working, I returned to UC Berkeley to study for a doctoral degree

第七天笔记

Uncaught (in promise) Neo4jError: WebSocket connection failure. Due to security constraints in your

Beifu PLC and C transmit bool array variables through ads communication

Google play app store may delete the overview of APP permissions and use a new combination of data security information
![[daily training] 814. Binary tree pruning](/img/c1/d71e6190a1855a392689b55503f75e.png)
[daily training] 814. Binary tree pruning
随机推荐
[daily training] 814. Binary tree pruning
Notes du jour 7
Jenkins continuous integration error stderr: fatal: unsafe repository ('/home/water/water' is owned by someone else)
【可视化调度软件】上海道宁为SMB组织带来NETRONIC下载、试用、教程
Functional testing to automated testing, sharing ten years of automated testing experience
Space shooting part 1: player spirit and control
Charles抓包工具测试实战
Beifu PLC and C transmit bool type variables through ads communication
倍福PLC和C#通过ADS通信定时刷新IO
Target segmentation for 10000 frames of video, with less than 1.4GB of video memory | eccv2022
DeFi 永不消亡?
使用fastjson解析以及赋予json数据时,json字段顺序不一致问题
Notes on the seventh day
[visual scheduling software] Shanghai daoning brings netronic downloads, trials and tutorials to SMB organizations
【JZOF】12矩阵中的路径
Numpy: quick start to basic operations
Intercept the specified range data set from list < map >
第十天笔记
[actf2020 freshman competition]backupfile 1
Debug No5基础光照