Home Web Front-end JS Tutorial How to achieve high-performance mobile development

How to achieve high-performance mobile development

Nov 18, 2017 am 10:53 AM
develop move high performance

As we all know, the mobile terminal should not only load quickly, but also have content without user experience. It should also run smoothly, such as quick-response interactions and silky-smooth animations...

How to achieve the above effects in actual development?

1. Confirm the analysis standards of rendering performance

2. Prepare a ruler to measure the rendering performance standards

3. Optimize the most time-consuming areas

We can roughly get the following optimization goals

How to achieve high-performance mobile development


The first one is the first screen presentation time. The online information has There are many, many, compressed codes, use webp images, use sprites, on-demand loading, "direct out", CDN...

The second one is 16ms optimization. This article focuses on 16ms optimization.


1. Browser renderingPrinciple introduction

The refresh frequency of most devices is 60 times/second, (1000/60 = 16.6ms) In other words, the browser's rendering of each frame must be completed within 16ms. Beyond this time, the rendering of the page will be stuck, affecting the user experience.

This is what is shown in the above picture

How to achieve high-performance mobile development

#If the attribute is changed further to the left in the above picture, the greater the impact and the lower the efficiency. .

The browser rendering process is as follows:

Get the DOM and split it into multiple layers (RenderLayer)

Rasterize each layer and draw it independently In the bitmap,

upload these bitmaps to the GPU as textures

Composite multiple layers to generate the final screen image (ultimate layer).

As can be seen from the above figure, if you just change the composite (merging of rendering layers), the efficiency will be greatly improved.

The following is a rough list of which styles will change which module of the rendering process.

How to achieve high-performance mobile development

#As you can see from the picture above, transform and opacity will only change composite (rendering layer merging). Why? Because GPU acceleration is turned on.

Turn on GPU acceleration

Literal explanation: Textures can be mapped to different locations at a very low cost, and they can also be applied to a very simple Transform into a rectangular grid.

[The literal understanding is very convoluted, but it is still the same old truth. Don’t use words if you can explain it clearly with pictures. 】

Small tips: First select a frame of the timeline, then select the layer label tab below, you can drag the module left and right to appear 3d

We can see that the page is composed of the following layers :

How to achieve high-performance mobile development

#Although what we end up seeing on the browser is just a copy, that is, there is only one layer in the end. Similar to the "layer" concept in PhotoShop software, all available view layers are finally merged and a picture is output to the screen

But in fact a page will Because some rules are divided into corresponding layers, once they are independent, they will not affect the layout of other DOM, because after it is changed, it is only "pasted" to the page.

Currently the following factors will cause Chrome to create layers:

3D or perspective transform (perspective transform) CSS properties

Use the

elements with 3D (WebGL) context or accelerated 2D context

Mixing plug-ins (such as Flash)

Do CSS animations on their own opacity or use an animation webkit-transformed elements

Elements with accelerated CSS filters

Elements have a descendant node that contains a composite layer (in other words, an element has a child element , the child element is in its own layer)

The element has a sibling element with a lower z-index and contains a composite layer (in other words, the element is rendered on top of the composite layer)

In webkit-based browsers, if the above situation occurs, an independent layer will be created.

Be careful not to create too many rendering layers, which means new memory allocation and more complex layer management. Don't abuse GPU acceleration, pay attention to whether composite layouts exceed 16ms

How to achieve high-performance mobile development

Having said so many principles of browser rendering, it is useless to measure without a ruler. So, let’s choose a ruler to measure: Timeline of Google development tools.


2. Common functions of Google development tool Timeline


1. After clicking Record in the upper left corner, the recording ends The following will be generated. The red area is the frame. Move up and you can see the frequency of each frame. If it is >60fps, it is relatively smooth.

How to achieve high-performance mobile development


2. Under the timeline, you can see the time-consuming of each module, and you can locate the time-consuming ones. Above the function, optimize the function.

How to achieve high-performance mobile development


3. Follow the steps below to select and you can see the independent layer and highlight the redrawn area, which is convenient Find the unnecessary redrawing areas and optimize them

How to achieve high-performance mobile development

After selection, the following 2 color borders will appear on the current page

Yellow border: Elements with animated 3D transformations are placed in a new composite layer (composited layer) to render

Blue grid: These blocks can be regarded as lower-level units than the layer, Chrome Taking these chunks as units, the content of one chunk is uploaded to the GPU at a time.

The tools are also available, and the principles of browser rendering are also known. The next step is to optimize based on actual projects.


3. Conduct in actual projects 16.6ms optimization

Combined with the above rendering flow chart, we can analyze and optimize the following steps

OptimizationJavaScriptexecution efficiency

Reduce the scope and complexity of style calculation

Avoid large-scale, complex layouts

Simplify the complexity of drawing and reduce the drawing area

Prioritize the use of rendering layer merging attributes, Number of control layers

Debounce processing function for user input events (mobile devices)


1. Separation of reading and writing, batch operations

## When the #JavaScript script is running, the element style attribute values ​​it can obtain are all from the previous frame, and they are all old values.

Therefore, if you make changes to the element node before obtaining the attributes in the current frame, it will cause the browser to first apply the attribute modifications, then execute the layout process, and finally execute the JavaScript logic.

// 先写后读,触发强制布局
function logBoxHeight() {
    // 更新box样式
    box.classList.add('super-big');
 
    // 为了返回box的offersetHeight值
    // 浏览器必须先应用属性修改,接着执行布局过程
    console.log(box.offsetHeight);
}
Copy after login

After optimization:

// 先读后写,避免强制布局
function logBoxHeight() {
    // 获取box.offsetHeight
    console.log(box.offsetHeight);
 
    // 更新box样式
    box.classList.add('super-big');
}
Copy after login


2. Closure cache calculation results (functions that require frequent calls and calculations)

getMaxWidth: (function () {
            var cache = {};
            function getwidth() {
                if (maxWidth in cache) {
                    return cache[maxWidth];
                }
                var target = this.node,
                 width = this.width,
                  screen = document.body.clientWidth,
                   num = target.length,
                  maxWidth = num * width + 10 * num + 20 - screen;
                cache[maxWidth] = maxWidth;
                 return maxWidth;
             }
             return getwidth;
})(),
Copy after login

After changing to this method, it just works~ It reduces more than 10 ms


3. Debounce the user input event processing function

If The touched element is bound to the input

event processing function, such as touchstart/touchmove/touchend, then the rendering layer merging thread must wait for the completion of the execution of these bound processing functions before it can be executed, that is, the user's scrolling page The operation is blocked, and the behavior is that the scrolling is delayed or stuck.

In short, you must ensure that any processing function bound to the user input event can be executed quickly to free up time for the rendering layer merger thread to complete its work.

Input event processing functions, such as scroll/touch event processing, will be called and executed before requestAnimationFrame. Therefore, if you modify the style attributes in the above input event handler, these operations will be temporarily stored by the browser.

Then when calling requestAnimationFrame, if you read the style attributes at the beginning, it will trigger the browser's forced synchronization layout operation (ie, perform layout in the javascript stage), so This will lead to multiple layouts and low efficiency.

Optimization is as follows:

window.requestAnimationFrame(function () {
    context.animateTo(nowPos);  //需要更新位置的交给RAF
});
Copy after login


4. Reduce unnecessary redrawing

Continuing from the above, after turning on paint flashing, you can see Which areas the browser repaints. I found that some unnecessary redrawing areas were also redrawn~ Enable GPU optimization for these (mentioned above)

Look at the timeline effect directly, it is all green~I finally let go of my hanging heart

How to achieve high-performance mobile development

How to achieve high-performance mobile development

There are many tips for mobile development. Today I will bring you this high-performance development tip. More For knowledge, please continue to pay attention to our website PHP.cn

Related reading:

Mobile terminal development: Handling the horizontal and vertical screens of mobile devices

Essential knowledge for mobile terminal development (reprint)_html/css_WEB-ITnose

Some tips for mobile development_html/css_WEB-ITnose

The above is the detailed content of How to achieve high-performance mobile development. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Four recommended AI-assisted programming tools Four recommended AI-assisted programming tools Apr 22, 2024 pm 05:34 PM

This AI-assisted programming tool has unearthed a large number of useful AI-assisted programming tools in this stage of rapid AI development. AI-assisted programming tools can improve development efficiency, improve code quality, and reduce bug rates. They are important assistants in the modern software development process. Today Dayao will share with you 4 AI-assisted programming tools (and all support C# language). I hope it will be helpful to everyone. https://github.com/YSGStudyHards/DotNetGuide1.GitHubCopilotGitHubCopilot is an AI coding assistant that helps you write code faster and with less effort, so you can focus more on problem solving and collaboration. Git

6000 mAh silicon negative battery! Xiaomi 15Pro upgrade leaked again 6000 mAh silicon negative battery! Xiaomi 15Pro upgrade leaked again Jul 24, 2024 pm 12:45 PM

According to news on July 23, blogger Digital Chat Station broke the news that the battery capacity of Xiaomi 15 Pro has been increased to 6000mAh and supports 90W wired flash charging. This will be the Pro model with the largest battery in Xiaomi’s digital series. Digital Chat Station previously revealed that the battery of Xiaomi 15Pro has ultra-high energy density and the silicon content is much higher than that of competing products. After silicon-based batteries are tested on a large scale in 2023, second-generation silicon anode batteries have been identified as the future development direction of the industry. This year will usher in the peak of direct competition. 1. The theoretical gram capacity of silicon can reach 4200mAh/g, which is more than 10 times the gram capacity of graphite (the theoretical gram capacity of graphite is 372mAh/g). For the negative electrode, the capacity when the lithium ion insertion amount reaches the maximum is the theoretical gram capacity, which means that under the same weight

Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Apr 07, 2024 am 09:10 AM

On March 3, 2022, less than a month after the birth of the world's first AI programmer Devin, the NLP team of Princeton University developed an open source AI programmer SWE-agent. It leverages the GPT-4 model to automatically resolve issues in GitHub repositories. SWE-agent's performance on the SWE-bench test set is similar to Devin, taking an average of 93 seconds and solving 12.29% of the problems. By interacting with a dedicated terminal, SWE-agent can open and search file contents, use automatic syntax checking, edit specific lines, and write and execute tests. (Note: The above content is a slight adjustment of the original content, but the key information in the original text is retained and does not exceed the specified word limit.) SWE-A

Learn how to develop mobile applications using Go language Learn how to develop mobile applications using Go language Mar 28, 2024 pm 10:00 PM

Go language development mobile application tutorial As the mobile application market continues to boom, more and more developers are beginning to explore how to use Go language to develop mobile applications. As a simple and efficient programming language, Go language has also shown strong potential in mobile application development. This article will introduce in detail how to use Go language to develop mobile applications, and attach specific code examples to help readers get started quickly and start developing their own mobile applications. 1. Preparation Before starting, we need to prepare the development environment and tools. head

Which Linux distribution is best for Android development? Which Linux distribution is best for Android development? Mar 14, 2024 pm 12:30 PM

Android development is a busy and exciting job, and choosing a suitable Linux distribution for development is particularly important. Among the many Linux distributions, which one is most suitable for Android development? This article will explore this issue from several aspects and give specific code examples. First, let’s take a look at several currently popular Linux distributions: Ubuntu, Fedora, Debian, CentOS, etc. They all have their own advantages and characteristics.

The new king of domestic FPS! 'Operation Delta' Battlefield Exceeds Expectations The new king of domestic FPS! 'Operation Delta' Battlefield Exceeds Expectations Mar 07, 2024 am 09:37 AM

"Operation Delta" will launch a large-scale PC test called "Codename: ZERO" today (March 7). Last weekend, this game held an offline flash mob experience event in Shanghai, and 17173 was also fortunate to be invited to participate. This test is only more than four months away from the last time, which makes us curious, what new highlights and surprises will "Operation Delta" bring in such a short period of time? More than four months ago, I experienced "Operation Delta" in an offline tasting session and the first beta version. At that time, the game only opened the "Dangerous Action" mode. However, Operation Delta was already impressive for its time. In the context of major manufacturers flocking to the mobile game market, such an FPS that is comparable to international standards

Exploring Go language front-end technology: a new vision for front-end development Exploring Go language front-end technology: a new vision for front-end development Mar 28, 2024 pm 01:06 PM

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Understanding VSCode: What is this tool used for? Understanding VSCode: What is this tool used for? Mar 25, 2024 pm 03:06 PM

"Understanding VSCode: What is this tool used for?" 》As a programmer, whether you are a beginner or an experienced developer, you cannot do without the use of code editing tools. Among many editing tools, Visual Studio Code (VSCode for short) is very popular among developers as an open source, lightweight, and powerful code editor. So, what exactly is VSCode used for? This article will delve into the functions and uses of VSCode and provide specific code examples to help readers

See all articles