In March 2018, nine major mobile phone manufacturers including Huawei, Xiaomi, and OPPO jointly released Quick Apps. The Quick App standard was jointly formulated by the Quick App Alliance composed of mainstream mobile phone manufacturers. It has the application experience of traditional apps, but also has the characteristics of no installation and click-to-use. In fact, as early as 2013, Baidu launched light applications. In 2017, Tencent launched mini programs. Later, Alibaba also launched Alipay's mini programs. In terms of business details, they are different, but the positioning is generally similar. Just like the transition from CS architecture to BS architecture, this form of application that does not require installation and can be used right away is becoming a new trend in the app market. Without further ado, let's get back to the main topic. The purpose of this article is to let everyone know the commonly used optimization methods for quick application development, improve the ability to organize application code, and reasonably split functional modules, so as to make the project easier to maintain and improve work efficiency. As for how to build a development environment, development process and system API description, you can find it in the official documentation of quick applications. This article will introduce the optimization techniques for quick application development. Quick application development uses the front-end technology stack, and its optimization methods can be mainly carried out from the following four aspects:
Data Sharing In the development of quick applications, developers need to understand how to share data between pages and apps, and between pages. In fact, not only quick applications, but any front-end project needs to consider this issue. For example, in react development, the introduction of redux can facilitate the unified management of data sources. In the development of quick applications, data sharing can be achieved by using framework APIs or global variables. 1. Framework API Developers can obtain the data and methods defined in the APP through this.$app.$def in the page ViewModel. But the disadvantage of this approach is that it needs to rely on ViewModel instances, however, many global methods are not related to the life cycle. As a reference independent of the application life cycle, the global variable global should be the developer's first choice. 2. Global variables In app.ux and ${anyPage}.ux, developers can use the global variable. However, the global variable is not the same between pages and apps, and between pages. The referenced values point to different objects. Although they are different, their prototypes all point to the same global object. Therefore, developers can define variables on this global object, which can be accessed in any JS. At the same time, this method also has disadvantages, such as polluting the global environment and causing difficult-to-reproduce bugs in complex scenarios. Performance Optimization 1. More reasonable Dom structure The Dom node is the most basic element of the page. Try to use semantically correct tags. Reducing the Dom hierarchy will significantly improve the readability and performance of the page. 2. More efficient selectors The development framework of quick apps supports descendant selectors, which provides great convenience for developers. However, at the same time, the performance loss of descendant selectors is relatively large. If used improperly, it will cause more loss to page performance. First of all, we need to know that CSS selectors are interpreted from right to left . Look at the following selector #container > a {font-weight:blod;} For many people who are just beginning to learn about CSS, they usually think that this selector first finds the element with the id of container, and then applies the font bolding effect to the a element in the direct child element, which should be an efficient selector. However, this is not the case. The browser will first find all the a elements in the page, and then filter out the nodes whose parent element id is container. So this seemingly efficient selector actually costs a lot of money. After understanding this rule, we recommend the following optimizations for the use of descendant selectors.
3. Image Optimization In front-end development, images usually occupy a large space. More image resources also mean more http requests. Under the same bandwidth conditions, downloading a 200k image is definitely faster than downloading 100k images twice. It is recommended to make a few optimizations.
4. Simplify the data properties of ViewModel Data-driven is a popular front-end development style, and this is also true in quick applications. In the definition of ViewModel, the data attribute is mainly responsible for data-driven data definition, and each attribute in the assigned data is recursively defined. Therefore, the clearer the semantic structure of the attribute definition and the fewer the number, the higher the quality. For example, when we issue a fetch request, the returned result contains a lot of data, but the data that the front end needs to display is only a small part of it. In the data of the page, we only need to define the data that the front end needs to display, as shown in the example code snippet below. // The data returned by the fetch request is large in size, but only part of the data is needed const tradeInfoList = [ { "_id" : "5c31aa2a565e9938214da13b", "currentPrice" : 1, "tradePrice" : 1, "userId" : "admin", "tradeAmount" : 600, "stockInfo" : { "code" : "000008", "name" : "Stock 8", "price" : 1, "des" : "Description 8" } }, { // ... } ] export default { data () { return { list: [] } }, onInit() { // Return the object properties required in the page, filter other properties this.list = tradeInfoList.map(item => { userId: item.userId, tradePrice: item.tradePrice }) } } 5. Lazy Loading Lazy loading is a common optimization method. In traditional H5 pages, lazy loading means that resources are loaded and the page is rendered only when the page is about to enter the visible area of the screen. In this way, the user can intuitively feel that the page loading speed has become faster. In the development of quick applications, instructions or event triggers can be used to implement lazy loading. For example, in a very common scenario, a page containing a list component, we start by rendering only the first ten pieces of data. When the page scrolls down to a certain position, it triggers loading more to complete the rendering. Error handling In front-end development, once an error occurs in program execution, a JS exception pop-up window will be displayed. 1. Accessing null or undefined properties The above error may be the most common one. In slightly complex business logic code, adding more null conditions is the easiest way to avoid this error. Even if some data must exist when defined, we cannot fully guarantee that there are various reasons that cause these data to be empty or undefined. Ensuring the rigor of the code is the fundamental way to deal with uncertainty exceptions. Of course, some slightly complex situations require special processing, such as the last two scenarios. 2. JSON.parse parsing error This error is also very common. When we convert a JSON string, if the format of the string is not a standard JSON format, the conversion will definitely fail. You can use try-catch to wrap it when JSON.parse() to analyze the error information, such as Of course, it would be a bit troublesome to execute try-catch in every place where JSON.parse() is called. The more recommended way is to proxy JSON.parse() in advance in app.ux and surround it with try-catch, such as export function parseProxy() { const rawParse = JSON.parse JSON.parse = function (str, defaults) { try { return rawParse(str) } catch (err) { console.error(`JSON parsing failed: ${str}, ${err.stack}`)return defaults } } } 3. Abnormal scenario of ViewModel callback function The user opens PageA, executes an interface method (such as a fetch request) in the page, and then immediately jumps to PageB; at this time, the callback function of the interface returns, but PageA has been popped out of the stack and destroyed. At this time, the callback function passed by the developer reports an error. This is because some data is accessed in the callback function, and the data attributes of these ViewModels have been deleted along with the page destruction, so an error is reported. For this exception, the following methods can usually be used to solve it. A. Before the callback function is executed, the page status is determined by the $valid and $visible of the ViewModel object. B. Define methods on Function.prototype and associate them with each callback function bound to the ViewModel instance. /** * Define the bindPage method on the Function prototype: bind the callback function to the page object. When the page is invisible or destroyed, the callback function is not executed*/ export function bindPageLC () { Function.prototype.bindPage = function (vmInst) { const fn = this return function () { if (!vmInst) { throw new Error(`Usage error: please pass VM object`) } if (vmInst.$valid && vmInst.$visible) { return fn(...arguments) } else { console.info(`When the page is invisible or destroyed, the callback function is not executed`) } } } } In ${anyPage}.ux, bind the ViewModel instance to the callback function through fn.bindPage(this) export default { data () { return {} }, request () { // Call bindPage(this) to return: the callback function bound to the page object. When the page is not visible or destroyed, the callback function is not executed. fetch({ success: function(ret) { //Data operations, etc.}.bindPage(this) }) } } C. Usually when a page sends a request, the page needs to add loading processing to prevent the user from performing other operations at this time. Of course, this method avoids this exception from a business perspective. However, it is a very common method. It can be combined with method B to ensure the rigor of the code. Structural Optimization The purpose of structural optimization is to reduce the size of the page and the entire rpk package and reduce redundant code The commonly used methods are as follows: A. Introduce commonly used JS libraries in app.ux and expose them to each page for use; this can avoid repeated definition of JS in each page when packaging B. Abstract encapsulation of code within the project, such as encapsulating commonly used tool functions and unified Fetch request methods. These encapsulations can be provided to each page as public methods, which facilitates maintenance and effectively reduces the amount of code. Conclusion The purpose of optimization is to improve the maintainability of the code and the performance of the application. It can be said that it is the various optimization methods that make the highly logical code full of artistry. In order to complete the coding more elegantly, I believe this topic will continue to be discussed. |
<<: 5G phones in 2019: expensive, battery-hungry, and not very useful
>>: 13 excellent Android security apps
In the wet market, we can always see all kinds of...
All major automakers are making driverless cars. ...
The official version of Android 7.1 will be offic...
The citrus family has a long-standing reputation ...
Nowadays, facing more and more information impact...
Why should you be an agent for WeChat Mini Progra...
With the rapid development of the new energy vehi...
For Xiaoxi (pseudonym), a 1-year-and-4-month-old ...
In fact, everyone has read a lot of useful inform...
2018 may be the year when everyone tried out TikT...
Reviewing past events is an essential skill for o...
Author: Tang Lingwen, Ye Rongzhen, Jian Yuting, Y...
Who is the most popular beverage in the beverage ...
Cherish life and stay away from AIDS!...
From Zibo barbecue to Tianshui spicy hot pot, eve...