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

How to achieve high-performance mobile development

php中世界最好的语言
php中世界最好的语言Original
2017-11-18 10:53:141653browse

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 39000f942b2545a5315c57fa3276f220 element to accelerate video decoding

5ba626b379994d53f7acf72a64f9b697 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);
}

After optimization:

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


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;
})(),

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
});


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:
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