[TOC]

preface

  • We were exploring earlierIOS animation and rendering principlesWhen, have learned:
    • Computer graphics rendering principle;
    • Mobile terminal screen imaging and Caton principle;
    • IOS rendering framework and iOS layer rendering principle;
  • There are several ways that we, as programmers, can learn to improve our level of technical competence. For example,Chain learning,Loop learning,Comparative learning methodAnd so on.
    • Obviously, we’re exploringIOS animation and rendering principles”Is used whenChain learning.
    • Next, in order to broaden our knowledge and make a relatively systematic understanding of the same subject, we will adoptLoop learning, to explore several related topics:
      • IOS -OffScreenRendering off-screen rendering principle
      • Causes and solutions of iOS CPU and GPU resource consumption
  • All of the above areiOS NativeFrom a development perspective, from another dimension,Of course we should pay attention to WebApps,Cross-platform developmentYou guessed right, I am here to use the comparative learning method, related topics:
    • Rendering principles for Web and Class RN large front ends
    • Flutter page rendering principle
    • Performance comparison of page rendering under three different technical schemes
  • Of course, in our era of technology ecology, ali, Tencent, Baidu and other big companies also launched small programs, so we should also pay attention to
    • This paper is to tell the rendering principle of small program framework page rendering principle and unfold!!

Small program:

  • Leader of wechat Business Department of TencentXiao-long zhangreleaseWechat appletsSince, the majority of Internet users have experienced the small program to bring short, flat, fast small program services. From then on, soWalking is followed,Use would be put on the finishThe light application mode of the Internet has set off a whirlwind in China.
  • followingWeChatThe pace of subsequent major Internet giants such asAlibaba, Baidu, JD.com, BytedanceAnd so have quit their own small program platform.
  • As a result, the mobile Internet ecosystem has further evolved into super APP + small program, which has become a new ecosystem in the era of light application. So what exactly is a small program? What about its rendering logic? Let’s explore it step by step.

What is applets?

Let’s introduce bytedance platform pairsByte appletsAn introduction to the official documentation of the

  • Applets are a new form of application.
  • The pattern of applets development is similar to Web development: Used JavaScript for development, CSS for styling control, and finally HTML for rendering.
  • However, we developed the small program JS code, is actually running in a called"Logical layer"In most cases, and each applet has one and only one “logical layer”.
  • In Web development, JS threads and render threads are mutually exclusive on each page;
  • In the small program, JS running process and rendering process (view layer) is independent, view rendering update, will not block JS execution, at the same time, JS logical execution, will not block view rendering update.
  • This leads to the first issue we need to be aware of:Js-driven views are updated asynchronously, and JS does not have direct access to the VIEW's DOM

In Web development, ourThe runtime environment is a browser, whether it is JS, or HTML/CSS, are running in the browser. So, for our Web pages, the variable environment is the browser, weYou may need to deal with the functionality and rendering differences of Web browsers such as Safari/Chrome/Firefox. And when we develop small programs, we also have to deal with differences in the operating environment, butApplets' environment differences refer to the differences in the projects of different applets' host platforms

Now let’s look at Ali’sAlipay small programA brief introduction to

Alipay mini program is a new open model, which provides partners with the opportunity to share the multi-terminal traffic and business capabilities of Alipay and Alibaba Group, providing users with better experience and helping merchants upgrade their business operations.

What is a small programHost (Platform Engineering)?

  • First of all, we know of a number of Internet giants with small program capabilities, such asAlibaba, Baidu, JD.com, BytedanceEtc.
  • Second, these companies have a lot of Internet products. weSmall program developer friendsAfter developing a small program for one of the platforms, you need to put it on that platform, and that platform will put the small program on their company’s Internet productsHost project that supports applets services.
  • thisReservoir engineeringIn fact, they are the main Internet products in different business directions, such as:Alibaba's AlipayAnd tencentWeChatAnd bytesTik Tok, ToutiaoEtc.

Conclusion:

Miniprogram is a lightweight application, a good idea to leverage the Internet giant’s user traffic to expand their business. It is a new situation that expands the Internet ecology at present. According to their own business positioning, Internet giants have withdrawn from their own small programs to help partners better operate their products and realize industrial ecological symbiosis. Applets are developed in a similar way to Web development, but more brief than the Web. Applets for different platforms depend on hosts for different platforms.

Each program platform provides a simple and efficient application development framework and rich components and APIS for developers, helping developers have better experience and service in the process of developing small programs. We are not going to address other issues of applets today, such as how applets are developed. Today, we mainly take wechat applets and Alipay applets as examples to discuss the rendering principle of the applets framework:

An overview of the

It is a general trend to build applications in the way of small program, and more and more enterprise users see its advantages. Enterprise users can use the user traffic of small program platform to promote their own platform. Build a small program to help enterprise users to build a small program ability of the “mobile portal” a new idea. At present, it is gratifying that some friends have practiced to build a small program development platform across multi-terminal platform, and harvested gratifying results. We can develop multiple sets of code without using different applets!!

Due to the prevalence of small programs, the Internet ecology has further evolved: Super APP + small programs become a new ecology in the “light application era”.Next, let’s take a look at the rendering principle of small procedures!

Content structure of this paper

Wechat mini program 2, Alipay mini program 3, summary 4, article recommended about reading (a total of 14 articles)

First, wechat small program

Before introducing the rendering principle of the applets framework, first of all, we have to return to the relevant introduction to the applets. When it comes to introducing the applets, we will first focus on their project structure

1.1 Project Structure

  • Page structure
    • The page structure file is index. WXML, which is written by wechat’s self-defined tag.
  • Page logic
    • The page logic is written in JavaScript.
  • Page style sheet
    • Like a CSS file, to define the style of elements in a page.
  • Configuration page
    • Configure information such as permissions on the page.

In the previous section, we mentioned that applets, regardless of platform, depend on the host (project) of the applets. So what exactly does the applets depend on in the host project? Let’s go step by step!!

1.2 Rendering of small programs

Techniques for rendering interfaces

Before introducing the rendering of applets, let’s take a look at two types of rendering:
  • Pure Native technology rendering
    • Disadvantages: Cannot be dynamically packaged and delivered.
  • Render using pure WebApp technology (page render and JS logic layer share one thread, and only one WebView)
    • Cons: If we render applets using pure Web techniques, we may face performance issues on pages with complex interactions
    • We discussed WebApp or RN-like rendering principles in another article, which mentioned WebKit rendering
    • In Web technology, BOTH UI rendering and JavaScript script execution are executed in a single thread, which makes it easy for some logical tasks to grab resources for UI rendering. ,

Applet technology is a Hybrid technology between pure Native and pure Web

  • A combination of client-side native and Web technologies to render (Web page renderingwithJS logic layerIt is executed by two separate threads without blocking.)
  • Wechat JSSDK such Hybrid technology, namely① The interface is mainly rendered by mature Web technology.Web resources can be hot updatedThe client native is complemented by a large number of interfaces(2) Provide abundant host engineering Native capabilities.
  • At the same time, wechat applets for the WebProvides Web page stack management:Each applet page is rendered with a different WebView, which can provide better interactive experience, more close to the native experience, but also avoid a single WebView too heavy task

A two-threaded model for applets

The rendering layer and logic layer of the applet are managed by two threads:
  • Rendering layerThe interface is rendered using WebView;
  • Logic layerRun JavaScript code with JSCore.
  • There are multiple interfaces in a small program, so there are multiple WebViews in the rendering layer (each WebView is rendered separately by WebKit). The communication between the two threads is transferred through the Native side of the applet, and the network request sent by the logical layer is also forwarded through the Native side. The communication model of the applet is shown in the following figure.

  • The view layerMainly responsible for page rendering
  • Logic layerResponsible for js execution
The view layerwithLogic layerCommunicate with each other through events and data.
  • Communication is a layer of transfer made by wechat client (Native);
  • And, host engineering –WeChatSmall programs also provide JSAPI(JavaScriptInterface), through jsBridge to call native function modules, such as: camera, scan code, HUD, network communication, data storage, Bluetooth and other functions.
    • Brief description of work flow: JS→JSCore→JSBridge(Native registration of JSCore callback,JSBridge is responsible for interpreting JS call signal, and then forward to specific Native implementation class)→ JSAPI provided by Native (access to specific Nat Ive function block)
  • thisThe view layerThe view layer currently uses the WebView as the rendering vehicle
  • The logic layer is made up of independent JsCore as the running environment of JS, so it is different from the browser. There are only some js corresponding methods, and dom cannot be directly operated and acquired. Communication layer is required in the middle. There is no channel for direct data sharing.
  • Currently, data transfer between the view layer and the logical layer 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.
  • Since they are independent and message-driven, they do not block the page; , my rendering will not affect your JS logic, JS execution will not plunger the rendering process;

For example, when we send some requests, this is usually forwarded by Native:

1.3 Design idea of two-line layer model of small program

For the sake of control and security, wechat mini program prevents developers from using some open interfaces provided by browsers, such as jumping to pages, manipulating DOM, and dynamically executing scripts. Separating the logical layer from the view layer, only data communication between the view layer and the logical layer can prevent developers from arbitrarily operating the interface, and better ensure user data security.

Wechat applet view layer is WebView, logic layer is JS engine. The three-end script execution environment and the environment used to render non-native components are different:

  • On iOS, iPadOS, and Mac OS, the javascript code in the applet logic layer runs in JavaScriptCore, and the view layer is rendered by WKWebView, IOS 14, iPad OS 14, Mac OS 11.4, etc.
  • On Android, the javascript code for the applet logic layer runs in V8, and the view layer is rendered by a self-developed XWeb engine based on the Mobile Chrome kernel.
  • On Windows, the small program logic layer javascript and the view layer javascript use the Chrome kernel.
  • On the development tool, the javascript code of the applet logic layer is run in nw.js and the view layer is rendered by Chromium Webview.
  • Mobile big front-end developers need to focus on three things:

Single WebView instancewithApplets with two threads and multiple instancesDifferences in code execution

  • In single WebView mode, Page view and App logic share the same JSContext, so that all pages can share global data and methods, and achieve global state management.
  • In multi-WebView mode, each WebView has an independent JSContext. Although data can be transmitted through window communication, data and methods cannot be shared, and the global state management is relatively complex.
    • Removing a generic WebView or JS Engine as the application’s JSContext solves these problems, but introduces other problems:How do views and logic communicateIn theIn the small program data update rear view is asynchronous update.
  • A diagram of the life cycle of a two-threaded application:

1.4 Page rendering of wechat applets

As we can know from the previous length, wechat mini program is every page has an independent WebView control to display, the whole small program page unified by wechat page stack management.

And separate WebView page rendering, WebKit rendering mechanism, overall and native control rendering process is not much different. I have made a detailed introduction in each iOS rendering framework and iOS layer rendering principle, Web and class RN large front-end rendering principle in two articles, you can go into two more detailed process. It differs from WebApp in that:

  • ①-WebApp uses a single page instance, which uses multiple WebView instances, so it is more portable, better rendering performance;
  • ②-WebAppJS logic layer and view layer are mixed together, which is heavy and relatively low maintainability. Its view layer and logic layer are independent, the code is more maintainable, and will not share a Context with JS, there will be no page rendering logic and JS logic block each other.

Two, Alipay small program

The implementation of Alipay applets is roughly the same as that of wechat applets, and the differences between the two are mainly discussed here.

Before introducing the rendering principle of Alipay small program framework, similarly, we first return to the relevant introduction of small programs. When it comes to introducing small programs, we first pay attention to its project structure:

2.1 Project Structure

2.2 Rendering of Alipay mini program

Like wechat applets, Alipay applets are Hybrid technologies between pure Native and pure Web, and also have a dual-thread model

Alipay small procedures of the dual – thread model

The rendering layer and logic layer of the applet are managed by two threads:
  • Rendering layerThe interface is rendered using WebView;
  • Logic layerRun JavaScript code with JSCore.
  • The view layerMainly responsible for page rendering
  • Logic layerResponsible for js execution
The view layerwithLogic layerCommunicate with each other through events and data.
  • Native does a layer of transfer;
  • And, host engineering –AlipaySmall programs also provide JSAPI(JavaScriptInterface), through jsBridge to call native function modules, such as: camera, scan code, HUD, network communication, data storage, Bluetooth and other functions.
    • Brief description of work flow: JS→JSCore→JSBridge(Native registration of JSCore callback,JSBridge is responsible for interpreting JS call signal, and then forward to specific Native implementation class)→ JSAPI provided by Native (access to specific Nat Ive function block)
  • thisThe view layerThe view layer currently uses the WebView as the rendering vehicle

Alipay Applet business Architecture diagram:

Better rendering engine

In terms of rendering engine, Alipay applet not only provides JavaScript+Webview, but also JavaScript+Native. In scenes with high performance requirements, Native rendering mode can be selected to give users a better experience

UC browser kernel is used

In ali’s mPaaS development kit, for H5 container rendering, on Android, developers can also choose to use the UC browser kernel instead of Google’s V8. And in the alipay host project, alipay’s developers are using the UC browser kernel. Here are the advantages of using this kernel:

  1. Image memory: For low-end computers, we have made a stricter limit on image cache, and further limit the use of image cache while maintaining performance experience

    • Image cache pool shared by multiple WebViews;
    • Fully support WebP, APNG this more memory – saving and size of the picture format.
  2. Rendering memory: Webview in the invisible state, the native memory management has no special treatment, UC kernel will not be visible Webview rendering memory release;

    • Reasonable Settings and tuning of render memory to avoid scrolling performance degradation and excessive memory usage.
  3. JS memory: More reasonable handling of V8 memory GC, delayed full GC at startup to avoid affecting startup time.

  4. Peak memory management: when the system is short of memory, it will notify the kernel. UC kernel can release non-critical memory occupying modules when the system is low in memory, avoiding OOM and rendering black blocks caused by excessive release.

    • In some OOM cases, avoid the native kernel active crash logic, and in extremely low memory cases, some features are unavailable, rather than crashing

2.3 Alipay small program VIRTUAL machine isolation

The usual way to do this is to run the Render code in the WebView, and then run the Serviceworker on another thread:

  • When the ServiceWorker needs to update the DOM, it sends events and data to the Render thread via messagechannel for execution.
  • When the business needs to transfer a large amount of data to the Render layer and the object is more complex, the performance of the interaction will be poor, so we propose an optimized solution for this situation.

The solution redesigns the ORIGINAL JS VIRTUAL machine instances (known as Isolate) into two parts: Global Runtime and Local Runtime.

  • The Global Runtime section houses shared devices and data, globally an instance.
  • The Local Runtime holds the instance’s own modules and private data, which will not be shared.

Under the new isolation model, the v8 instance in webView is a Local Runtime, and the V8 instance in worker thread is also a Local Runtime. When the worker layer interacts with the Render layer, SetData objects are created directly in the Shared Heap, so the Render layer’s Local Runtime can read the object and use it for rendering.Reduced object serialization and network transfer, greatly improved startup performance and rendering performance.

2.4 Optimization of the first screen startup of Alipay mini program

Since applets are subject to lifecycle control, go from onLaunch -> onLoad -> onShow -> onReady -> User action -> Off home page. Any link in this process is likely to be interrupted by objective or subjective reasons, which may lead to inaccurate offline pages saved and wrong pages presented to users at startup.

Therefore, for the effect of offline cache rendering of the home page, the timing of saving the page is very important. Alipay small program provides developers with the opportunity to configure, and the timing of configuration has two: the completion of rendering and before leaving the home page. \

  • forRender the completeThat is, the page is saved as an offline cache before the user performs any operation after the home page rendering is completed.
  • Before leaving the home pageAfter a user performs a series of operations on the home page, the user is redirected to another page, which is saved as an offline cache.

The scene where the flash screen problem occurs is becauseThe cached page is separated from the actual rendered pageThe cached page is a static page, while the real page is dynamically created by JS. Therefore, the common practice is to replace the cached page after the creation of the real page. In this case, the flash screen will occur.To solve this problem, the Alipay team adopted the virtual DOM to put the cached page into the initial virtual DOM when loading the cached page. Dom diff was performed between the virtual DOM generated after the creation of the real page and the virtual DOM of the cached page. The changed content is transmitted to the browser kernel through patch to render the corresponding page, so that only partial changed page content can be updated, avoiding the update of the whole page, and ensuring the accuracy and real-time of the content.

Third, summary

Through the previous introduction, we basically know:

  • Applets are all in betweenPure WebandPure NativeHybrid technology between;
  • The small programThe view layerandLogic layerThe separation,The view layerEach of theA small program pageThere areA single WebView instancePage management is managed through the page stack manager
  • Native provides capabilities for applets through JSAPI. In the framework layer, the host project also provides JSBridge tools for communication and interaction between Native and small program H5.
  • In comparison, alipay applet has done some optimization work compared with wechat applet:
    • Provides better rendering mechanics;
    • The UC browser kernel is used
    • Optimized the first screen boot
    • Virtual machine isolation “two sets of Runtime” for applet dock

The unsolved problems in this article are as follows:

  • 1. Discuss how to carry out the agile development of small program;
  • 2. Interpretation of small program framework;
  • 3. Interpretation of small program source code;
  • 4. Small program actual combat project experience sharing
  • .

reference

  • Wechat applets development document

  • Micro channel applet principle document

  • Alipay small program development document

  • Alipay small procedures to achieve

4. Article recommendation

  • 01- The most practical micro channel small program daquan, continue to update…
  • 02- Strongly recommended several micro channel small program development tips, simple and practical
  • 03- How is developing applets using UNI-App better than developing applets directly native?
  • 04- Applets development: Native or framework (WEPY/MPvue/Uni-app/Taro)?
  • 05- New era of full stack development of applets

Related reading (14 articles in total)

  • On principle of 01 – computer | computer graphics rendering this article
  • 02 – | mobile terminal screen computer imaging and caton

IOS related Topics

  • 01 – iOS | the underlying principle of iOS rendering framework and principle of iOS layer rendering
  • 02 – iOS underlying principle | iOS animation rendering principle
  • 03 – iOS underlying principle | iOS OffScreen Rendering off-screen Rendering principle
  • 04 – iOS underlying principle | caton caused by CPU and GPU resources consumption reasons and solutions

WebApp related topics

  • 01- Rendering principles for Web and Class RN large front ends

Topics related to cross-platform development solutions

  • 01-Flutter page rendering principle

Stage summary: Performance comparison of Native, WebApp and cross-platform development schemes

  • 01- Performance comparison of Native, WebApp and cross-platform development schemes

Android and HarmonyOS page rendering features

  • 01-Android page rendering principle
  • 02-HarmonyOS page rendering principles (For the output)

Small program page rendering thematic

  • 01- Applets framework rendering principle

conclusion

  • 01- Big front-end technology collocation and selection of the project scheme (For the output)
  • 02- Thoughts on stack accumulation for big front-end engineers (For the output)