High-performance mobile development and high-performance development

Source: Internet
Author: User

High-performance mobile development and high-performance development

Without knowing it, the Spring Festival is over, and there is no time to enjoy it. I really want to go on a trip without blowing water, and directly go to the topic.

I recently made a demand and found a weak point. I 'd like to take this opportunity to gain a deeper understanding and broaden my horizons ~

 

As we all know, web pages should not only be quickly loaded, but also run smoothly, such as fast response interactions and smooth animations ......

In actual development, how can we achieve the above results?

1. Confirm the rendering performance analysis criteria 2. Prepare a ruler to measure Rendering Performance Standards 3. Optimize time-consuming places We can roughly obtain the following optimization objectives:

The first is the presentation time of the first screen. There are already a lot of online materials. We need to compress the code, use webp images, use sprite, load as needed, "Direct-out", CDN ......

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

 

1. Introduction to browser rendering principles

The refresh frequency of most devices is 60 times/second, (1000/60 = 16.6 ms), that is, the rendering of each frame by the browser must be completed within 16 ms, page rendering will be stuck., Affecting user experience.

This is in <16 ms. The browser performs the following actions in one frame. Of course, some steps (such as layout and paint) can be omitted.

If you change the attribute to the left in the figure above, the greater the impact, the lower the efficiency.

The rendering process of the browser is as follows:

As shown in the figure above,If you only change composite (rendering layer merging), the efficiency will be greatly improved.

The following roughly lists which styles will change the rendering process.

From the perspective of transform, opacity only changes composite (rendering layer merging). Why? Because GPU acceleration is enabled.

  Enable GPU AccelerationLiterally, textures can be mapped to different locations at a very low cost, and they can be transformed by applying them to a very simple rectangular mesh at a very low cost. [The literal understanding is very difficult to understand. It is still the old principle. You can use a picture to clarify the truth and do not use text .]

Small tips: select firsttimelineAnd then selectlayerLabel tab, you can drag the module left or right to see 3d

The page consists of the following layers:

 

Although we finally see only a copy in the browser, that is, there is only one layer.Similar to the "layer" concept in PhotoShop software, merge all the visible layers and output an image to the screen.

But in fact, a page will be divided into corresponding layers because of some rules. Once it is isolated, it will no longer affect the layout of other dom, because after it changes,Paste.

 

Currently, the following factors will cause Chrome to create a layer:
  • 3D or perspective transform CSS attributes
  • Decoded using a CDN video<video>Element
  • With 3D (WebGL) context or accelerated 2D Context<canvas>Element
  • Hybrid plug-ins (such as Flash)
  • Perform CSS animation on your opacity or use an animated webkit transform element.
  • Elements with accelerated CSS Filters
  • An element has a child node that contains a composite layer (in other words, an element has a child element in its own layer)
  • An element has a sibling element with a lower z-index and a composite layer (in other words, this element is rendered on the Composite Layer)
  • In the webkit kernel browser, if the preceding conditions are met, an independent layer is created.

Note that do not create too many rendering layers, which means new memory allocation and more complex layer management. Do not abuse GPU acceleration. Check whether the composite layouts exceeds 16 ms.

 

 

Speaking of the rendering principles of so many browsers, it is useless to measure without a ruler. Then, choose the ruler to measure: Timeline of Google's development tool.

2. Common functions of Timeline, a Google Development Tool

1. Click "Recording" in the upper left corner. The following figure is generated after the recording is completed. The frame is in the red area. You can see it when you move it.The frequency of each frame, if> 60fps, is relatively smooth. If it is <60fps, it will feel stuck..

 

2. In timeline, we can see the time consumed by each module,You can locate the time-consuming function.To optimize the function.

3. follow the steps below to select, that is You can see independent layers and highlighted areas,This helps you identify areas that do not need to be re-painted and optimize them.

After selection, the current page displays the colored border in the following two Yellow border:Element with animated 3d transform, indicating that it is rendered in a new composited layer Blue raster: These chunks can be seen as lower-level units than the layer. Chrome uploads a chunk of content to the GPU at a time in units of these chunks.

The tool also has the principle of browser rendering, and the next step is to optimize it based on the actual project.

3. 16.6 ms Optimization in actual projects

Based on the rendering flowchart above, we can analyze and optimize the following steps.

  • Optimize JavaScript execution efficiency
  • Reduce the scope and complexity of style computing
  • Avoid large-scale and complex la s
  • Simplify the rendering complexity and reduce the rendering Area
  • The paintlayer merging attribute and number of control layers are preferred.
  • Dejitters the processing functions of user input events (mobile devices)

 

1. read/write splitting and batch operations

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

Therefore, if you modify the Element Node before obtaining the attribute of the current frame, the browser must first apply the Attribute Modification, execute the layout process, and then execute the JavaScript logic.

// Write and read first, triggering the forced layout function logBoxHeight () {// update the box style box. classList. add ('super-big '); // to return the box's offersetHeight value // the browser must first apply the Attribute Modification and then execute the layout process console. log (box. offsetHeight );}
After optimization:
// Read and write first to avoid forcing the layout of function logBoxHeight () {// get box. offsetHeight console. log (box. offsetHeight); // update the box style box. classList. add ('super-big ');}

 

2. Closure cache calculation results (frequently called, computed functions)
 1 getMaxWidth: (function () { 2             var cache = {}; 3             function getwidth() { 4                 if (maxWidth in cache) { 5                     return cache[maxWidth]; 6                 } 7                 var target = this.node, 8                     width = this.width, 9                     screen = document.body.clientWidth,10                     num = target.length,11                     maxWidth = num * width + 10 * num + 20 - screen;12                 cache[maxWidth] = maxWidth;13                 return maxWidth;14             }15             return getwidth;16 })(),

After this method is changed, the system will immediately seek help ~ Reduced by more than 10 ms

  3. dejitters the processing functions of user input eventsIf the elements to be touched are bound with input event processing functions, such as touchstart/touchmove/touchend, the merging thread of the rendering layer must wait until the bound processing functions are executed, that is, the user's page rolling operation is blocked, and the behavior is delayed or choppy. 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 merge thread to complete his 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 processing function, these operations will be saved by the browser.

Then, when you call requestAnimationFrame, if you read style attributes from the beginning, this will trigger the forced synchronization layout operation of the browser (that is, executing the layout in the javascript phase), which will lead to multiple la S and low efficiency.

 

The optimization is as follows:

Window. requestAnimationFrame (function () {context. animateTo (nowPos); // submit the updated location to RAF });
  4. Reduce Unnecessary re-painting

On the top of the page, after you enable painting, you can see which areas the browser has re-drawn. Some areas that do not need to be re-painted are also re-painted ~ Enable GPU Optimization for these (as mentioned above)

Check the timeline effect. It's all green ~ The Hanging heart is finally put down

 

 

 

Reference: http://www.jianshu.com/p/a32b890c29b1

 

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.