A detailed description of Web page performance management

Source: Internet
Author: User
Tags chrome developer chrome developer tools chrome devtools

Have you ever encountered a poorly performing web page?

This web page responds very slowly, consumes a lot of CPU and memory, browsing often has a lag, the page animation effect is not smooth.

How would you react? I suspect that most users will close this page and visit other websites instead. As a developer, you certainly don't want to see this situation, how can you improve performance?

This article details the cause of the performance problem and how to resolve it.

First, the process of Web page generation

To understand why Web page performance is not good, it is necessary to understand how the Web page is generated.

The process of generating a Web page can be roughly divided into five steps.

    • HTML code into DOM
    • CSS code converted to CSSOM (CSS Object Model)
    • Combine DOM and CSSOM to create a rendering tree (with visual information for each node)
    • Build layout to plane synthesize all nodes of all render trees
    • Draw the layout (paint) on the screen

In these five steps, the first and third steps are very fast and time-consuming are steps fourth and fifth.

The two steps, build layout (flow) and draw (paint), collectively referred to as render.

Second, rearrange and redraw

When a page is generated, it is rendered at least once. The process of user access also continues to be re-rendered.

The following three scenarios cause the Web page to be re-rendered.

    • Modifying the DOM
    • modifying style Sheets
    • User events (such as mouse hover, page scrolling, input box type text, change window size, etc.)

Re-render, you will need to regenerate the layout and redraw. The former is called "rearrangement" (reflow), which is called "redrawing" (repaint).

It is important to note that "redraw" does not necessarily require "reflow", such as changing the color of a page element, only triggering "redraw" and not triggering "reflow" because the layout has not changed. However, "reflow" inevitably results in "redrawing", such as changing the position of a page element, triggering "reflow" and "redraw" as the layout changes.

Third, the impact on performance

Reflow and redraw are constantly triggered, which is unavoidable. However, they are very resource-intensive and are the root cause of poor Web page performance.

Improve Web page performance is to reduce the "reflow" and "redraw" the frequency and cost, as little as possible to trigger re-rendering.

As mentioned earlier, DOM changes and style changes will trigger a re-rendering. However, the browser is already very smart, will try to put all the changes together, into a queue, and then one-time execution, try to avoid multiple re-rendering.

Div.style.color = ' Blue ';d iv.style.marginTop = ' 30px ';

In the above code, the DIV element has two style changes, but the browser only triggers a single reflow and redraw.

If it is not well written, it will trigger two reflow and redraw.

Div.style.color = ' blue '; var margin = parseint (div.style.marginTop);d Iv.style.marginTop = (margin + ten) + ' px ';

After the above code sets the background color for the DIV element, the second line requires the browser to give the element a position, so the browser has to rearrange it immediately.

In general, after a style is written, the browser is immediately re-rendered if there are read operations for the following properties.

    • Offsettop/offsetleft/offsetwidth/offsetheight
    • Scrolltop/scrollleft/scrollwidth/scrollheight
    • Clienttop/clientleft/clientwidth/clientheight
    • getComputedStyle ()

Therefore, from a performance perspective, try not to read and write operations, put in a statement inside.

Baddiv.style.left = Div.offsetleft + + "px";d iv.style.top = div.offsettop + + "px";//Goodvar left = Div.offsetle Ft;var top  = Div.offsettop;div.style.left = left + ten + "px";d iv.style.top = top + + "px";

The general rules are:

    1. The simpler the style sheet, the quicker it will reflow and redraw.
    2. The higher the level of DOM elements that reflow and redraw, the higher the cost.
    3. Table element Reflow and redraw costs are higher than DIV elements
Iv. Nine tips for high performance

There are some tricks that can reduce the frequency and cost of browser re-rendering.

The first one is that the DOM has multiple read operations (or multiple write operations) that should be put together. Do not add a write operation between the two read operations.

Second, if a style is re-queued, it is best to cache the result. Avoid the next time you use it, your browser will have to rearrange it again.

Third, do not change the style, but by changing the class, or Csstext properties, one-time changes in style.

Badvar left = 10;var top = 10;el.style.left = left + "px"; el.style.top  = top  + "px";//good El.classname + = "T Heclassname ";//Goodel.style.cssText + ="; Left: "+ left +" PX; Top: "+ top +" px; ";

Fourth, try to use the offline DOM instead of the real web dom to change the element style. For example, manipulate the Document Fragment object and then add the object to the DOM when you are done. For example, use the CloneNode () method to operate on the cloned node, and then replace the original node with the cloned node.

Fifth, the element is set to Display:none (1 reflow and redraw required), then 100 operations are performed on the node, and then the display is restored (1 reflow and redraw required). This allows you to re-render two times instead of possibly up to 100 times.

Sixth, the Position property is a absolute or fixed element, and the cost of rearrangement is small because it does not take into account the effect it has on other elements.

Seventh, only when necessary, the display property of the element is visible, because invisible elements do not affect reflow and redraw. In addition, the elements of Visibility:hidden only have an effect on rearrangement, and do not affect redrawing.

Eighth, the use of Virtual DOM script library, such as React.

Nineth, use Window.requestanimationframe (), Window.requestidlecallback () These two methods to adjust the re-rendering (see below).

Five, refresh rate

In many cases, intensive re-rendering is unavoidable, such as callback functions for scroll events and Web page animations.

Each frame of a Web page animation is re-rendered at once. Less than 24 frames per second of animation, the human eye can feel the pause. General web animation, need to reach 30 frames per second to 60 frames of frequency, in order to be more fluent. If you can reach 70 frames or even 80 frames per second, it will be extremely smooth.

Most displays have a refresh rate of 60Hz, and in order to be consistent with the system and conserve power, the browser automatically refreshes the animation (if possible) at this frequency.

Therefore, if the Web page animation can be 60 frames per second, it will be synchronized with the monitor refresh, to achieve the best visual effect. This means that 60 re-renders within one second and no more than 16.66 milliseconds per re-render.

The number of times a second can be re-rendered, this indicator is called "refresh rate", English FPS (frame per second). 60 re-renders, which is 60FPS.

Vi. Timeline Panel for developer tools

The Timeline panel of the Chrome developer Tools is the best tool for viewing "refresh rate". This section describes how to use this tool.

First, press F12 to open the developer tools and switch to the Timeline panel.

There is a gray dot in the upper left corner, which is the record button, and pressing it will turn red. Then, do something on the page and press the button once to complete the recording.

The Timeline panel is available in two viewing modes: the "event Mode", which shows the time spent on the various events being re-rendered, and the "frame mode" of the vertical bar, showing where each frame's time is spent.

Look at the "event pattern" and you can tell what the performance problem is, whether it's JavaScript execution or rendering?

Different colors represent different events.

  • Blue: Network communication and HTML parsing
  • Yellow: JavaScript Execution
  • Purple: Style calculation and layout, that is, reflow
  • Green: Redraw

which color block is more, it shows that performance is spent there. The longer the color block, the bigger the problem.

Frame mode (Frames mode) is used to view the time-consuming situation of a single frame. The lower the height of the color bar per frame, the better it is, which means less time consuming.

As you can see, there are two levels of reference lines in the frame mode.

The following one is 60FPS, below this line, can reach 60 frames per second, the above one is 30FPS, below this line, can reach 30 times per second rendering. If the color column is more than 30FPS, this page has a performance problem.

In addition, you can view the time-consuming situation for an interval.

Or click on each frame to see the frame's time composition.

Vii. Window.requestanimationframe ()

There are some JavaScript methods that can adjust the re-rendering to dramatically improve Web page performance.

The most important of these is the Window.requestanimationframe () method. It can put some code into execution the next time it is re-rendered.

function Doubleheight (Element) {  var currentheight = element.clientheight;  Element.style.height = (Currentheight * 2) + ' px ';} Elements.foreach (Doubleheight);

The above code uses a looping operation to increase the height of each element by one-fold. However, each loop is followed by a write operation followed by the read operation. This triggers a lot of re-rendering in a short period of time, which is obviously bad for Web page performance.

We can use it to window.requestAnimationFrame () separate the read and write operations and put all the writes to the next re-render.

function Doubleheight (Element) {  var currentheight = element.clientheight;  Window.requestanimationframe (function () {    element.style.height = (Currentheight * 2) + ' px ';  }); Elements.foreach (Doubleheight);

Page scrolling event (scroll) of the listener function, it is appropriate to use Window.requestanimationframe (), deferred to the next re-rendering.

$ (window). On (' scroll ', function () {   window.requestanimationframe (scrollhandler);});

Of course, the most suitable for the occasion is web animation. Here is an example of a rotation animation, where the element rotates 1 degrees per frame.

var RAF = Window.requestanimationframe;var degrees = 0;function Update () {  div.style.transform = "rotate (" + degrees + "deg)";  Console.log (' updated to degrees ' + degrees);  degrees = degrees + 1;  RAF (update);} RAF (update);
Viii. Window.requestidlecallback ()

There is also a function window.requestidlecallback (), which can also be used to adjust the re-rendering.

It specifies that the callback function is executed only if there is idle time at the end of a frame.

Requestidlecallback (FN);

In the above code, the function FN executes only if the current frame is running at less than 16.66ms. Otherwise, postpone to the next frame, and if the next frame has no idle time, postpone to the next frame, and so on.

It can also accept the second parameter, which represents the specified number of milliseconds. If there is no idle time for each frame during the specified period of time, the function FN will be enforced.

Requestidlecallback (FN, 5000);

The code above indicates that the function FN will be executed at the latest after 5000 milliseconds.

The function FN can accept a deadline object as a parameter.

Requestidlecallback (function someheavycomputation (deadline) {while  (deadline.timeremaining () > 0) {    Doworkifneeded ();  }  if (Thereismoreworktodo) {    requestidlecallback (someheavycomputation);  }});

In the above code, the Someheavycomputation parameter of the callback function is a deadline object.

The deadline object has a method and a property: Timeremaining () and didtimeout.

(1) timeremaining () method

The Timeremaining () method returns the milliseconds remaining in the current frame. This method is read-only, cannot be written, and is dynamically updated. Therefore, you can constantly check this property, and if there is time remaining, perform certain tasks. Once this attribute is equal to 0, the task is assigned to the next round requestIdleCallback .

In the preceding example code, the Doworkifneeded method is called continuously as long as there is idle time in the current frame. Once there is no idle time, but the task is not fully implemented, it is assigned to the next round requestIdleCallback .

(2) Didtimeout property

The properties of the deadline object didTimeout return a Boolean value that indicates whether the specified time expires. This means that if the callback function is triggered by a specified time expiration, you will get two results.

    • The Timeremaining method returns 0
    • Didtimeout property equals True

Therefore, if the callback function executes, there are two reasons: the current frame has idle time, or the specified time is up.

function Mynonessentialwork (deadline) {while  ((deadline.timeremaining () > 0 | | deadline.didtimeout) && Tasks.length > 0)    doworkifneeded ();  if (Tasks.length > 0)    requestidlecallback (mynonessentialwork);} Requestidlecallback (Mynonessentialwork, 5000);

The above code ensures that the Doworkifneeded function is bound to be repeated over time (or after a specified time expires) in the future.

Requestidlecallback is a very new function that has just introduced the standard and is currently only supported by Chrome.

Nine, reference links
    • Domenico De Felice, how browsers work
    • Stoyan Stefanov, Rendering:repaint, Reflow/relayout, Restyle
    • Addy Osmani, improving Web App performance with the Chrome DevTools Timeline and Profiles
    • Tom Wiltzius, Jank Busting for Better Rendering performance
    • Paul Lewis, Using requestidlecallback

A detailed description of Web page performance management

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.