High-performance mobile development

Source: Internet
Author: User

Unconsciously, the Spring Festival is over, have not had time to enjoy it. Good to want to say walk on the trip??, do not blow water, directly into the topic.

Recently in a need to find a weak place, take advantage of this good opportunity to learn more about, broaden the field of vision ~

It is well known that Web pages should not only be loaded quickly, but also run smoothly, such as fast-response interactions such as silky smooth animations ...

In the actual development how to achieve the above-mentioned effect?

1. Identify the analysis criteria for rendering performance 2. Prepare the ruler to measure the rendering performance standard 3. Optimize for time-consuming areas we can get a rough idea of the following optimization goals

The first is the first screen rendering time, the online data has been very much, compressed code, using WEBP pictures, using sprites, on-demand loading, "straight out", CDN ...

The second one is 16ms optimization, this article focuses on 16ms optimization.

I. Introduction to the principle of browser rendering

most of the device refresh frequency is 60 times/second, (1000/60 = 16.6ms) is also said that the browser for each frame of the rendering work to complete in 16ms, beyond this time, the page rendering will appear in the phenomenon of Kaka, affecting the user experience.

This is the <16ms in the middle. browser in a frame, will do the following actions. Of course, some steps (such as Layout,paint) can be omitted.

If you change the attribute to the left in the above image, the effect is greater and the efficiency is lower.

The process for browser rendering is as follows:

    1. Get DOM and split it into multiple layers (renderlayer)
    2. Rasterize each layer and draw the carry-on chart independently
    3. Upload these bitmaps to the GPU as textures
    4. Compound multiple layers to produce the final screen image (the ultimate layer).

As you can see from the above picture, If you just change the composite (render layer merge), the efficiency will be greatly improved.

The following is a rough list of which modules to change which styles change the rendering process individually.

You can see that transform,opacity only changes the composite (render layer merge), why? Because GPU acceleration is turned on.

turn on GPU accelerationThe literal explanation: textures can be very low-costMappingTo different locations and can be deformed at a very low cost by applying them to a very simple rectangular mesh. "The literal understanding is very much around the mouth, or the old truth, can use the figure to clear the truth not to use the text." 】

Small tips: First select a timeline frame, and then select the following layer tab tab, you can drag the module appears around 3d

We can see that the page consists of the following layers:

Although what we finally see in the browser is only a copy version, that is, eventually only one layer. similar to the "layers" concept in Photoshop software, finally merging all visible layers, outputting a picture to the screen

But in fact a page will be divided into the corresponding layer because some rules , once independent, it will no longer affect the layout of other Dom, because it changed, just " paste " the page.

The following factors are now causing the chrome layer to be created:
    • 3D or Perspective Transform (Perspective transform) CSS Properties
    • Elements that use accelerated video decoding <video>
    • Elements that have a 3D (WebGL) context or an accelerated 2D context <canvas>
    • Hybrid plugins (such as Flash)
    • Do CSS animations on your own opacity or use an animated WebKit transform element
    • Elements that have accelerated CSS filters
    • An element has a descendant node that contains a composite layer (in other words, an element has a child element in its own layer)
    • The element has a sibling element that has a lower z-index and contains a composite layer (in other words, the element is rendered above the composite layer)
    • In the WebKit kernel browser, if this is the case, a separate layer is created.

It is important to note that you do not create too many render layers, which means new memory allocations and more complex layer management. Do not misuse GPU acceleration, pay attention to see if the composite layouts exceeded 16ms

With so many browser rendering principles, it's useless to measure without a ruler. Then, the following to choose a ruler to measure: Google Development tools timeline.

two. Common features of Google development tools Timeline

1. Click on the top left corner of the recording, after the recording will generate the following, the red area is the frame, moving up can see the frequency of each frame, if >60fps, is more fluent, if <60fps, will feel the lag .

2. Below the timeline, you can see the time-consuming of each module, which can be located to the time-consuming function above , to optimize the function.

3. Follow the steps below to select you can see the independent layer, highlight the redrawn area,Easy to find areas that don't have to be redrawn for optimization

After selection, the following 2 color border appears in the current page Yellow border:An element with an animated 3d transform that is rendered in a new composite layer (composited layer) the blue grid: These tiles can be thought of as a lower-level unit than a layer, in which Chrome uploads one chunk of content to the GPU at a time.

Tools are also available, the principle of browser rendering is also known, followed by the actual project optimization.

three. 16.6ms optimization in the actual project

Combined with the above rendering flowchart, we can analyze and optimize some of the following steps

    • Optimize the execution efficiency of JavaScript
    • Reduce the range and complexity of style calculations
    • Avoid large-scale, complex layouts
    • Simplifies drawing complexity and reduces drawing area
    • Prioritize the use of render layers to merge attributes, control levels
    • Handling function jitter for user input events (mobile device)

1. Read/write separation, batch operation

When the JavaScript script runs, it gets the element style property values that are the previous frame, all of which are old values.

Therefore, if you make a change to the element node before the current frame gets the property, it will cause the browser to have to apply the property modification, result in the layout process, and then execute the JavaScript logic.

Write first read, trigger force layout function logboxheight () {    //update box style    box.classList.add (' Super-big ');    In order to return the Offersetheight value of box    //The browser must first apply the property modification, then perform the layout procedure     console.log (box.offsetheight);}  
After optimization:
// Read and write first, avoid forced layout function logboxheight () {    //  get box.offsetheight    console.log (box.offsetheight);     // update box style    Box.classList.add (' Super-big ');}

2. Closure Cache calculation results (requires frequent calls, computed functions)
1 Getmaxwidth: (function () {2             var cache = {}; 3             function getwidth () {4                 if (MaxWidth in Cach e) {5                     return } 7 var target = this. node, 8 width =the. Width, 9 screen = Document.body.clientWidt h,10 num = target.length,11 maxWidth = num * width + ten * num +- screen;12 cache[maxwidth] = maxwidth;1 3 return }15 return getwidth;16}) (),            

Change to this way, the direct rub rub ~ reduced more than 10 ms

3. Process function jitter for user input eventsIf the touched element is bound to an input event handler, such as Touchstart/touchmove/touchend, then the render-layer merge thread must wait for the bound handler to execute before executing, i.e. the user's scrolling page operation is blocked. The behavior is that there is a rolling delay or Kaka. In short, you must ensure that user inputany handler for event binding can be executed quickly, freeing up time for the render layer to merge threads to complete his work。 Input event handlers, such as the handling of Scroll/touch events, are invoked before requestanimationframe. Therefore, if you have modified the style attributes in the handler for the input event above, then these actions will be staged by the browser.

Then, when calling Requestanimationframe, if you did the reading of the style property at the beginning, it would trigger a forced synchronous layout of the browser (that is, the layout in the JavaScript phase), which would result in multiple layouts and inefficiencies.

The optimizations are as follows:

Window.requestanimationframe (function  () {    context.animateto (nowpos);  Need to update the location to the RAF});
4. Reduce unnecessary repainting

Continue, after you turn on paint flashing, you can see which areas the browser has redrawn. Found that there are some unnecessary redraw areas also redrawn ~ to these turn on GPU optimizations (mentioned above)

directly see timeline effect, all green ~ hanging heart finally put down

Reference article: HTTP://WWW.JIANSHU.COM/P/A32B890C29B1

High-performance mobile development

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.