"From Jane book" Browser ~ load, parse, render

Source: Internet
Author: User
Tags prefetch

Yesterday in order to understand how the browser handles (. html,. css,. js) These files, I read a lot of information on the Internet, many of which are reproduced, or reproduced after the addition of their own understanding,

But because of their own professional vocabulary understanding is not good, there are some authors will be different browser processing process to say, in short, after reading, there are many doubts about the place.

I first based on what I learned yesterday, the future with the deep learning, and then back to add.

WhyWhy should I understand the process of browser loading, parsing, rendering?
    • To understand how the browser load , we can refer to external style files, external JS, put them in the appropriate location, so that the browser as fast as possible to load the file completed.
    • To understand how the browser is parsed , we can choose the best way to improve the resolution rate of the browser when building the DOM structure and organizing CSS selectors.
    • Understand how the browser renders , understand the process of rendering, we set the element properties, writing JS file, you can reduce the "redraw" "re-layout" consumption.
      These three processes are not completely independent at the time of actual implementation, but will have a crossover. Will cause one side to load, while parsing, while rendering the work phenomenon.
HowHow does a browser load, parse, and render?
    1. The user visits the webpage, the DNS server (domain name resolution System) will find the corresponding IP address according to the domain name provided by the user, and when found, the system will send an HTTP request to the network server corresponding to the IP address.
    2. The network server resolves the request and sends a request to the database server.
    3. The database server returns the requested resource to the network server, the network server parses the data, and generates an HTML file that is placed in the HTTP response and returned to the browser.
    4. The browser resolves the HTTP response.
      The 1~4 step requires an understanding of the HTTP protocol.
      Possible problems accessing the server side: If the network server cannot get the resource file returned by the database server (HTTP response 404), or if the user's HTTP request is temporarily unable to process for concurrency reasons (HTTP response 500)
    5. After the browser resolves the HTTP response, it is necessary to download the HTML file, as well as the external reference files contained within the HTML file, and the pictures or multimedia files involved in the file.
The following content is relatively complex O (∩_∩) o~

About loading order: when the browser obtains an HTML file, it loads "top-down" and parses the render during the loading process.

Loading

That is, the process of getting the resource files, different browsers, and their different versions when implementing this process, there will be different implementations (between resources blocking each other). (need to learn to use timeline to do the test, I am not very good at using, learned in the above.) )

<! DOCTYPE html><Html><Head><Metacharset="Utf-8" ><LinkRel="Stylesheet"href="Test.css"Type="Text/css"/><script src=  "test.js" type= "Text/javascript" ></script> </head> < body> <p> block </p> < IMG src= "test.jpg"/> </body></HTML>     

An external CSS file was encountered during the loading process, and a request was made by the browser to get the CSS file.
When you encounter a picture resource, the browser also makes a separate request to get the picture resource.

This is an asynchronous request that does not affect the loading of the HTML document, but when the document is loaded, the HTML document suspends the thread that renders the rendering (load parsing render synchronization) when it encounters the JS file.

Not only wait for the document to load the JS file, but also wait for the resolution to complete before you can restore the HTML document render thread.

Reason: JS has the possibility to modify the DOM, the most classic document.write, which means that before the completion of JS execution, all subsequent downloads of resources may not be necessary, which is the root cause of JS blocking the subsequent download of resources.
Method: You can put the external reference JS file </body> before.

Although the CSS file loading does not affect the JS file loading, but it affects the execution of the JS file, even if there is only one line of code in the JS file, it will cause blocking.

Cause: There may be var width = $ (' #id '). Width (), which means that before the JS code executes, the browser must ensure that the CSS file has been downloaded and parsed. This is also the root cause of CSS blocking subsequent JS.
Method: When the JS file does not need to rely on the CSS file, you can put the JS file in front of the head CSS.

Of course, <link href="" /> in addition to this form, the internal <style></style> definition of this style should be considered when considering blocking.
The above for the code layout of the impact of the document loading is relatively basic , with the browser upgrade, as well as the application of JS technology, HTML development, Web performance will gradually improve.
To list, you can expand it later:

  • do not call a long-running function in a JS file that is called externally, and you can use the SetTimeout function if you must.

    1. browser GUI render thread
    2. javascr IPT engine thread
    3. browser timer trigger thread (setTimeout)
    4. browser Event Trigger thread
    5. browser http asynchronous request thread (. jpg &NBSP; <link/> such a request)
      Cause: The browser has more than five resident threads
      Discover the 3rd thread, we know that If you use settimeout () within JS, then another thread is called.
      Note : This also involves &NBSP; blocking   phenomenon, when the JS engine thread (the second), will suspend all other threads, this time 3, 4, 5 these three thread threads will also produce different asynchronous events (this sentence does not understand AH), because JavaScript engine thread is single-threaded, so the code is first pressed to the queue, in the first-out way to run, the event handler function, the timer function will be pressed in the queue, constantly from the team head out of the event, this is called: Javascript-event-loop.
  • Modern browsers exist prefetch optimization, the browser will open another thread, pre-download JS, CSS files, it should be noted that the pre-loading JS does not change the DOM structure, he left this work to the main load.

  • Pre-load the Web page and use your free time to load the page's subsequent pages in advance.
    <link rel="prefetch" href="http://">
  • Add the defer attribute to the JS script so that the browser does not wait for the JavaScript script to load and then load the image behind it. Since the picture resources have been loaded out, do not write document.write in JS.
    <script defer="true" src="JavaScript.js" type="text/javascript"/>
parsing

There are many concepts to parse, and you need to write another article. So I'm going to write it down briefly.

    • HTML Document parsing generates a parse tree, the DOM tree, consisting of DOM elements and attribute nodes, and the root of the tree is the document object.

      DOM: The abbreviation of the Document Object model, which is the object representation of the HTML document, is used as the external interface of the HTML for JS invocation.

      document.getElementById (' Test '). style.display= "None";//the display value of ID test is set to none through the DOM interface.

    • CSS parsing parses a CSS file into a style sheet object. The object contains a CSS rule that contains selectors and declaration objects.

    • CSS parsing. png
    • JS parsing Because the file is loaded at the same time to parse, see the JS loading section.
Rendering

This is the process of building a rendering tree, which is a visual representation of the original Dom tree, which is constructed to draw the contents of the document in the correct order.
The relationship between the render tree and the DOM tree, the Invisible DOM element ( display=none ) is not inserted into the render tree.

There are also locations like some nodes that are absolute or floating (requires CSS knowledge), which are outside the text flow, so they are located in different locations on two trees, the render tree identifies the real location, and a placeholder structure identifies their original location.

one of the biggest difficulties with rendering is that each DOM node is calculated to match his final style.
    • To find a matching style rule for each element, you need to traverse the entire rule table. I was wrong about the way to traverse the rules table.
      #test p{ color:#999999}
      Positive Solution : The traversal is from right to left, that is, the first query to the p element, and then find the previous level ID test element. The previous understanding is just the opposite. In this way, the efficiency of traversal is very low.
      Why : You can go to see before the CSS parsing, the resulting style object, the order of traversal, is naturally from the low end of the tree to traverse.

Some difficulty in calculating styles:

  1. Style data is a very large structure, so it is very memory-intensive to keep the data.
  2. The selector iteration is too deep, causing too much useless traversal.
  3. Style rules involve very complex cascading, defining the hierarchy of rules (understanding that the external style sheet referenced in the table is replaced by the setting of the same property in the local style sheet. There are settings such as internal pairs that would have been body font applied to the child element, but if the child element of the body defines the font attribute, it will be replaced by the latter.

Workaround: Share style data. (The condition that elements can share style data is that their state is "consistent".) )

WebKit Rendering

The process of calculating styles and generating render objects is attachment, each DOM node has a attach method, the attachment process is synchronous, and the Attach method that invokes the new node is inserted into the DOM tree.
Parser: Parsing, render tree: Rendering trees layout: arranging layouts


WebKit main flow. png

During rendering, WebKit uses a flag to flag all top-level styles that have been loaded, and if the DOM element is attach, the CSS element is not loaded, then the placeholder is placed and marked in the document and recalculated when the style sheet is loaded.
Description, the rendering of the document is still waiting for the top-level CSS to load. The next gecko should also wait for the top level CSS to be loaded, otherwise the "CSS rules tree" (see below) cannot be built.

Gecko Rendering

WebKit rendering is the process of matching an element to a style rule, and gecko needs to build a style calculation rule book and then generate the number of style contexts (and the render tree) corresponding to the DOM tree. Example:

<Html><Body><Divclass="Err"Id="Div1″><P> this is a<Spanclass="Big" > Big error</Span> This is also a<span class= "big" > Very big Error </span> </ p> </div> <div class=  "err" id= "div2″> another error" Span class= "Hljs-tag" ></div> </ body></html>//rule 1. div {margin : 5px;color:black} 2. . err {color:red} 3. . Big {margin-top:3px} 4. Div span {margin-bottom:4px} 5. #div1 {Color:blue} 6. #div2 {color:green}              

style rule tree. png

Explain: A: any parent element. B, E: Represents the element selector, and B refers to the span under the div div,e. C, G: Represents the class selector. D, F: Rep: id selector. The following 123456, which represents the matching rule.


style context tree. png

Explain: When encountering a DOM node, for example: the second Div, according to the CSS parsing results, the rule matching found in accordance with 126 of this rule line,

We found that when we encountered the first div we had already matched 12 of this rule line, so we simply added a new node to the DIV:F node of the style context tree for rule 6. The style context tree, which is the final result of the element matching style (originally proportional to the specific px).

Gecko uses the style rule tree to realize the style sharing effectively. WebKit There is no rule tree, you need to iterate through the results of CSS parsing multiple times. Properties that occur more than once will be processed in the correct cascade order and the last one takes effect.

Based on our understanding of the difficulty of calculating styles, we should be careful when writing CSS stylesheets:

  1. Dom depth is as shallow as possible.
  2. Reduce the number of inline JavaScript and CSS.
  3. Use modern, legitimate CSS properties.
  4. Do not specify the class name or label for the ID selector because the ID can uniquely identify an element.
  5. Instead of assigning tags to class selectors, classes, which represent labels with a class of attributes, are not only one, although they can be implemented, but reduce efficiency.
  6. Avoid descendant selectors and use sub-selectors as much as possible. Cause: The probability of a child-element match is greater than the descendant-element-match character. Descendant selector, #tp p{} sub-selector: #tp >p{}
  7. Avoid using wildcards, for example,. mod. HD *{font-size:14px;} depending on the matching order, wildcards are first matched, that is, wildcard characters are matched first, and then matched. HD (that is, to traverse all the nodes on the DOM tree for his parent element), and then match. MoD, This performance cost is conceivable.

"From Jane book" Browser ~ load, parse, render

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.