For Web page rendering, that's something that every front-end developer should know.

Source: Internet
Author: User
Tags border color css preprocessor

"Editor's note" In fact, there are many articles about Web page rendering, but the relevant information is more scattered, and the discussion is not very complete. If we want to have a general understanding of this topic, we have to learn a lot of knowledge. As a result, web developer Alexander Skutin decided to write an article. He believes that this article will not only help beginners, but also to those who want to refresh the knowledge structure of the advanced front-end developers have some benefit. Original address

The translation is as follows:

Web page rendering must be done at an early stage, as early as the page layout has just been finalized. Because styles and scripts can have a critical impact on Web page rendering. Therefore, professional developers must understand some of the techniques to avoid encountering performance problems in the process of practice.

This article does not look at the detailed mechanisms inside the browser, but rather presents some common rules. After all, different browser engines work differently, which will undoubtedly make it more complicated for developers to study browser features.

How does a browser complete Web page rendering?

First, let's review the browser's actions when the page is rendered:

    1. form the Document Object Model (DOM) based on the HTML code from the server side
    2. Load and parse styles to form a CSS object model.
    3. On top of the Document Object model and CSS object model, create a render tree that consists of a set of objects to be rendered (in WebKit, these objects are referred to as renderers or render objects, and are called "frame" in gecko. The render tree reflects the structure of the Document object model, but does not include invisible elements such as labels or display:none attributes. In the render tree, each piece of text string behaves as a separate renderer. Each Render object contains a corresponding Dom object, or block of text, plus a computed style. In other words, a rendering tree is a visual representation of a Document object model.
    4. For each element on the render tree, calculate its coordinates, called the layout. The browser takes a stream method, layout an element only once, but the table element needs to pass multiple times.

    5. Finally, the elements on the render tree are finally displayed in the browser, a process called "painting".

When the user interacts with the Web page, or when the script changes the page, some of the actions mentioned earlier will be repeated, as the intrinsic structure of the page has changed.

Redraw

When changing the element style that does not affect the position of the element in the page, such as background-color (background color), Border-color (border color), visibility (visibility), the browser will only redraw the element once with the new style (this is redrawing, or re-structuring the style).

Re-arrange

Reflow or re-layout occurs when the change affects the text content or structure, or the position of the element. These changes are usually triggered by the following events:

    • Dom manipulation (element additions, deletions, modifications, or changes in the order of elements);
    • Changes in content, including changes in text within a form field;
    • The calculation or change of CSS properties;
    • Add or remove style sheets;
    • Change the properties of the class;
    • Operation of the browser window (zoom, scroll);
    • Pseudo-Class activation (: hover).
How does the browser optimize rendering?

As much as possible, the browser restricts redrawing/refactoring to the area of the element being changed. For example, for a fixed or absolute position, the size change affects only the element itself and its child elements, however, the change in the size of the statically positioned element triggers the heavy flow of all subsequent elements.

Another optimization technique is that when you run a few pieces of JavaScript code, the browser caches the changes and then applies the changes once the code has finished running. For example, the following code will only trigger a refactoring and redraw:

var $body = $(‘body‘);$body.css(‘padding‘, ‘1px‘); // reflow, repaint$body.css(‘color‘, ‘red‘); // repaint$body.css(‘margin‘, ‘2px‘); // reflow, repaint// only 1 reflow and repaint will actually happen

However, as mentioned earlier, changing the attributes of an element triggers a mandatory rearrangement. This behavior can occur if we include a line of code in the block above to access the attributes of the element.

var $body = $(‘body‘);$body.css(‘padding‘, ‘1px‘);$body.css(‘padding‘); // reading a property, a forced reflow$body.css(‘color‘, ‘red‘);$body.css(‘margin‘, ‘2px‘);

The result is that the rearrangement occurred two times. Therefore, you should organize the operations that access element properties together to optimize Web page performance. (You can find more detailed examples in Jsbin.)

Sometimes, you have to trigger a mandatory reflow. For example, we must assign the same attributes (such as the left margin) two times to the same element. At first, it should be set to 100px, and it does not drive the effect. Next, it must be changed to 50px by the Transition (transition) dynamic effect. You can now learn this example on Jsbin, but I'll introduce it in more detail here.

First, we create a CSS class with transition effects:

.has-transition {

-webkit-transition:margin-left 1s ease-out;
-moz-transition:margin-left 1s ease-out;
-o-transition:margin-left 1s ease-out;
Transition:margin-left 1s ease-out;
}

Then continue to execute:

Our element is a "has-transition" class by defaultVar $targetElem = $ ( ' #targetElemId '); //Remove the transition class $targetElem. Removeclass ( ' has-transition '); //change the property expecting the transition to be off, as the class was not There//anymore $targetElem. css ( ' Margin-left ', Span class= "Hljs-number" >100); //put the Transition class Back $targetElem. addclass ( ' has-transition '); //Change the Property $targetElem. CSS ( 50);        

However, this implementation is not effective. All changes are cached and executed only at the end of the code block. What we need is a mandatory rearrangement, which we can implement with the following changes:

Remove the Transition class$ (This ). Removeclass (' has-transition ');  Change the property$ (this). css (' margin-left ', + );  Trigger a forced reflow, so the changes in a Class/property get applied immediately$ (this) [0].offsetheight; 
              
               //An example, other properties would work, too
               //Put the Transition class back$ (this). addclass (' Has-tran Sition '); //Change the property$ (this). css (' margin-left ', + );       
              

The code now executes as expected.

Practical recommendations for performance tuning

Summing up the existing information, I make the following recommendations:

    • Create a valid HTML and CSS file, and don't forget to specify how the document is encoded. The style should be contained within the tag, and the script code should be added to the end of the tag.
    • Try to simplify and optimize the CSS selector (this optimization is almost uniformly ignored by developers using CSS preprocessor) to keep the nesting level to a minimum. The following is the performance ranking of the CSS selector (starting with the fastest person)

      1. Recognizer: #id
      2. Class:. class
      3. Tags: div
      4. Adjacent Brother selector: A + I
      5. Parent class selector:ul> Li
      6. Universal selector: *
      7. Attribute selection: input[type= "text"]
      8. Pseudo-class and pseudo-elements: a:hover

You should keep in mind that the browser handles selectors in the right-to-left principle, so the right-most selector should be the fastest: #id或则. Class:

div * {...} // bad.list li {...} // bad.list-item {...} // good#list .list-item {...} // good
    • 1. In your scripting code, minimize DOM operations. Caches everything, including element attributes and objects (if they are reused). When complex operations are performed, it is better to use the "orphaned" element, which can then be added to the DOM (the so-called "orphaned" element is detached from the DOM and stored only in memory).

    • 2. If you use jquery to select elements, follow the jquery selector best practices scenario.

    • 3. In order to change the style of an element, modifying the properties of the "class" is one of the methods that works. When this change is performed, the darker the DOM rendering tree is, the better (which also helps to detach the logic from the façade).

    • 4. Try to animate only the absolute or fixed elements of the position.

    • 5. Disable complex hover action when using scrolling (for example, add an extra non-hover class in). Readers can read an article on the subject.

To learn more about the details, you can also look at these two articles:

    • 1.How browsers work?
    • 2.rendering:repaint, Reflow/relayout, Restyle

For Web page rendering, that's something that every front-end developer should know.

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.