Why do each front-end developer understand the rendering of the page?

Source: Internet
Author: User
Tags css preprocessor

rendering should be optimized from the very beginning when page layouts are defined, and styles and scripts play a very important role in page rendering. Professionals know some tricks to avoid some performance problems. This article does not delve into the technical details of the browser, but rather provides some general principles. Different browser engines work differently, which complicates the learning of specific browsers.

How does the browser render a page?

let's start with the approximate process of rendering a page from a browser:
    • The HTML that is received from the server forms the DOM (Document Object model).
    • The style is loaded and parsed to form the CSSOM (CSS object model).
    • The DOM and CSSOM create a rendering tree, which is a collection of objects that are rendered (Webkit call them "renderer" and "Render Object", which is called "frame" in the Gecko engine). In addition to invisible elements such as head tags and some elements with Display:none attributes, the render tree maps the structure of the DOM. In the render tree, each text string is treated as a separate renderer. Each Render object contains a DOM object (or a block of text) that corresponds to the computed style. In other words, the rendering tree describes the intuitive representation of the DOM.
    • For each rendering element, its coordinates are computed, which is called "layout". The browser uses a "flow method" that only needs to be processed once to lay out all elements (tables needs to be processed multiple times).
    • Finally, the layout is displayed in the browser window, and this process is called "Drawing (painting)".

Redraw

When you modify some styles on the page that do not need to change the positioning (such as background-color,border-color,visibility), the browser simply redraws the new style to the element (this is called "redraw" or "redefine style").

Re-arrange

reflow (or "re-layout") occurs when changes on the page affect the document content, structure, or element positioning. The rearrangement is usually triggered by the following changes:
    • DOM operations (such as adding, deleting, changing, or altering the order of elements).
    • Changes in content, including text in form forms.
    • Calculates or alters a CSS property.
    • Adds or deletes a style sheet.
    • Change the "class" attribute.
    • The operation of the browser window (resizing, scrolling window).
    • Activates pseudo-classes (such as: hover state).

How does the browser optimize rendering?

The Browser does its best to limit the reflow process to overwrite only the area of the element that has changed. For example, a position is a absolue or fixed element whose size changes affect only its own and descendant elements, and doing the same for a position element that is static causes the rearrangement of all elements behind it. Another optimization is when running a section of Jjavascript code, the browser will cache some changes, and then when the code executes, a one-time implementation of these changes. For example, this code triggers one redraw and one reflow:
    1. var $body = $ (' body ');
    2. $body. css (' padding ', ' 1px '); Rearrange, redraw
    3. $body. CSS (' Color ', ' red '); Redraw
    4. $body. CSS (' margin ', ' 2px '); Rearrange, redraw
    5. Only one reflow and redraw is actually performed.

As mentioned above, accessing the attributes of an element is forced to reflow once. If we add a line to the code above to read the element's attributes, this will happen:
    1. var $body = $ (' body ');
    2. $body. css (' padding ', ' 1px ');
    3. $body. css (' padding '); This reads the attributes of the element once, and a forced reflow occurs.
    4. $body. CSS (' Color ', ' red ');
    5. $body. CSS (' margin ', ' 2px ');
The result of the above code is that it has been re-queued two times . So, in order to improve performance, you should say that the code that reads the attributes of the elements is organized together (the example of detail can look at the code on Jsbin). There is a case where a forced rearrangement must be triggered. For example: Change the same attribute to the element two times (for example, Margin-left), set 100px at the beginning, no animation, and then change the value to 50px in the form of animation. See examples, of course, I will tell you more details here. let's start with a transition CSS class:
    1. . has-transition {
    2. -webkit-transition:margin-left 1s ease-out;
    3. -moz-transition:margin-left 1s ease-out;
    4. -o-transition:margin-left 1s ease-out;
    5. Transition:margin-left 1s ease-out;
    6. }

Then implement the following:
  1. Our element defaults to the "Has-transition" property
  2. var $targetElem = $ (' #targetElemId ');
  3. Delete the class containing the transition
  4. $targetElem. Removeclass (' has-transition ');
  5. Change element properties when the class containing transition is gone
  6. $targetElem. CSS (' margin-left ', 100);
  7. Add the class containing transition back
  8. $targetElem. addclass (' has-transition ');
  9. changing element properties
  10. $targetElem. CSS (' Margin-left ', 50);
the above implementation did not run as expected. All of the changes are cached by the browser and will only be executed at the end of the code above. What we need is a forced rearrangement, which we can do by making the following modifications:
  1. Delete the class containing the transition
  2. $ (this). Removeclass (' has-transition ');
  3. changing element properties
  4. $ (this). CSS (' margin-left ', 100);
  5. Triggers a forced reflow so that the changed class or attribute can be executed immediately.
  6. $ (this) [0].offsetheight; Offsetheight is just an example, and other attributes can work.
  7. Add the class containing transition back
  8. $ (this). addclass (' has-transition ');
  9. changing element properties
  10. $ (this). CSS (' Margin-left ', 50);

Now this code is running as we expected.

Practical recommendations for optimization

summarizing some useful information, I suggest the following points:
    • Create legitimate HTML and CSS, and don't forget to make the file code, the Style should be written in the head tag, and the script tag should load the end of the body tag.
    • Try simplifying and optimizing the CSS selector (this optimization point is ignored by most developers using the CSS preprocessor). Controls the number of nesting layers to a minimum. The following are the performance rankings for CSS selectors (from the fastest start):
  • ID Selector: #id
  • Class selector:. Class
  • Tags: div
  • Adjacent sibling elements: A + I
  • Parent element selector: ul > li
  • Wildcard selector: *
  • Pseudo-class and pseudo-elements: a:hover, you should remember that the browser processing selector is right-to-left, which is why the rightmost selector is faster-#id或. class.
    1. div * {...}//Bad
    2. . List Li {...}//Bad
    3. . List-item {...}//Good
    4. #list. List-item {...}//Good
    • In your script, try to reduce the DOM's operation as much as possible. Cache everything, including attributes and objects (if it can be reused). When doing complex operations, it is best to manipulate an "offline" element (the "offline" element means that it is separate from the DOM object, only the memory element exists), and then insert the element into the DOM.
    • If you use jquery, follow the jquery selector best practices
    • To change the style of an element, modifying the "class" attribute is one of the most efficient ways. The more you change the level of the DOM tree, the more efficient it is (which also helps to separate performance from logic).
    • Animate only the elements of position, absolute or fix, as much as possible.
    • When scrolling, disable some complex: Hover animations are a good idea (for example, add a No-hover class to the body tag) article on this topic.
 

Why do each front-end developer understand the rendering of the page?

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.