preface

I am busy recently, so the update is a little slow, please understand! Then introduce the knowledge that interview digs deeply for everybody, the teleprompter content of relevant knowledge point!Copy the code

What happens from entering the URL to displaying the page?

This question is a must test, we should pay attention to! The interviewer can dig a lot out of this question, and you need to be prepared.Copy the code

When we get the URL, we do the DNS domain name resolution, we get the domain name, we get the IP address of the server, we set up TCP connections based on the transport layer above the IP layer, and then the HTML back from the server can be transmitted, multiplexing TCP connections under HTTP2.0, we can get CSS resources in parallel, This enters the browser rendering process

  1. After entering the URL, DNS domain name resolution is performed to find the corresponding IP address (what is DNS? How does DNS resolve?
  2. Establishing a TCP connection (three-way handshake and four-way wave)
  3. The server returns the HTML resource
  4. Start parsing the HTML and finish building the DOM tree
  5. Then parse CSS to complete the construction of CSSDOM tree ()
  6. Combine DOM tree and CSSOM tree to generate Render tree
  7. The GUI thread completes the pixel-level drawing
  8. Layout The web page layout takes effect
  9. The BFC layout is top-down

Url to page Rendering (top)

positioning

DNS domain name resolution => IP protocol => TCP connection establishment (three-way handshake, four-way wave)

Url to page Rendering (part 2)

Look at the browser rendering process and performance optimization from 8 interview questions

Browser rendering process and performance optimization

Critical path rendering optimization for front-end performance optimization

Browser multi-process architecture

Multi-process browsers break up different types of browser tasks and put them into different processes to perform them. Each process contains multiple threads, and multiple threads in a process will work together to complete the responsibilities of the process.

All threads of the renderer process

GUI rendering thread
  • Responsible for rendering browser interface
    • Parsing HTML, CSS
    • Build DOM trees and CSSOM trees
    • The DOM tree and the CSSOM tree are combined into a RenderObject tree
    • Layout and drawing
  • Responsible for performing redraw and reflow operations
  • The GUI rendering thread and the JS engine thread are mutually exclusive, the GUI thread is suspended (frozen) while the JS engine is executing, and GUI updates are stored in a queue until the JS engine is idle.
JS engine thread
  • JavaScript engine, also known as JS kernel (e.g. V8 engine)

  • Responsible for handling JavaScript script programs.

  • The JS engine waits for tasks to arrive in the task queue and then processes them

    There is only one JS thread running on a Tab page (renderer process) at any one time.

  • The GUI rendering thread and the JS engine thread are mutually exclusive, so if the JS execution time is too long, the page rendering will be incoherent and the page rendering load will block.

Event trigger thread
The message queue
  • Macro task
  • Micro tasks
Network asynchronous thread
Timer thread

Key render path

The rendering process by which the browser receives the HTML, CSS, and JavaScript bytes returned from the server and parses them and turns them into pixels is called the critical rendering path. By optimizing key render paths, you can shorten the browser rendering time.

  1. Parsing the HTML file, building the DOM tree, while the main browser process is responsible for downloading the CSS file (not blocking parsing of the DOM tree, but blocking rendering of the DOM tree)

    bytes => characters => tokens => nodes(objects) => dom/cssom

    Byte data => Encoding => tokenization => Production object => spanning tree

    • Encoding: The raw bytes of HTML data are first converted to the characters specified in the file encoding.

    • Tokenization: The browser then converts the string into tokens according to the HTML specification (tags such as < HTML >, , strings and attributes in tags are converted into tokens, each with a special meaning and a set of rules). Tokens record the beginning and end of tags. This feature makes it easy to determine whether a tag is a child tag (assuming that there are two tags, < HTML > and , when the < HTML > tag token encounters the tag token before it encounters its closing token
      ). Then is a child tag of < HTML >.

    • Generate objects: Each token is then transformed into an object (the node object) that defines its properties and rules.

    • Completion: The DOM tree is completed, and the entire collection of objects looks like a tree structure. One might wonder why the DOM is a tree structure, because there are complex parent-child relationships between tags, and the tree structure interprets this relationship (CSSOM, cascading style also contains parent-child relationships). For example, div p {font-size: 18px} will look for all p tags and determine if the parent tag is div before deciding whether to render in this style.

  2. The RenderObject tree is created by combining the DOM tree with the RenderObject tree.

Invisible nodes do not need to be rendered to the page. Invisible nodes also include nodes whose display: None property is used by CSS. Note that the visibility is undefined: The hidden property is not an invisible property, its semantics are to hide the element, but the element still occupies layout space, so it is rendered as an empty box.

  1. Draw the RenderObject tree (Paint), drawing the pixel information of the page

  2. Layout (BFC)

  3. The browser main process hands the default layers and composite layers to the GPU process, which then composes the layers and displays the page.

Pay attention to

DOM tree and CSSOM tree are parsed in parallel. CSS loading will not block parsing of DOM tree, but will block rendering of DOM tree. DOM tree must wait until rendering of CSSOM tree is complete (i.e., after loading of CSS resource or CSS resource fails) to start rendering, and then synthesize rendering tree together

Why does CSS or JS block rendering?
  • JS

    Because JavaScript is DOM manipulable, if you render the interface while modifying these element attributes (that is, the JavaScript thread and the UI thread are running at the same time), you might get inconsistent element data before and after the render thread.

    So to prevent unexpected results from rendering, the browser sets the GUI rendering thread (DOM/CSSOM parsing the rendering) to be mutually exclusive with the JavaScript engine.

    When the browser executes a JavaScript program, the GUI rendering thread is stored in a queue until the JS program completes execution.

  • CSS

    DOM tree and CSSOM tree are parsed in parallel. CSS loading will not block parsing of DOM tree, but will block rendering of DOM tree. DOM tree must wait until rendering of CSSOM tree is complete (i.e., after loading of CSS resource or CSS resource fails) to start rendering, and then synthesize rendering tree together

    CSS blocks DOM tree rendering as well as JS execution.

The difference between DOMContentLoaded and Load?
  • When there is no script in the document, the browser parses the document and fires the DOMContentLoaded event. If a script is included in the document, the script blocks parsing of the document, and the script can’t be executed until the CSSOM build is complete. In any case, DOMContentLoaded triggers without waiting for other resources such as images to complete loading.
  • When the onLoad event is triggered, all the DOM, stylesheet/script/image resources on the page have been loaded.
  • DOMContentLoaded => load
The DOM to load | | CSS file JS file loading sequence

Build: parse + render

  • Parse the HTML file and start building the DOM tree

  • When the tag is encountered, the browser will send a request for the CSS file of the tag (download the CSS file). This does not block DOM tree parsing, but will block DOM tree rendering.

  • The CSSOM tree is built

  • Continue building the DOM tree

  • When the

    Each time the JavaScript script is executed, it will severely block the DOM tree construction. If the JavaScript script also operates on a CSSOM that has not been downloaded and built, the browser will even delay the script execution and DOM construction until the CSSOM has been downloaded and built. So when we put the script tag before the link tag, we find that we can't get the DOM structure, and if we manipulate the CSS, we build the CSSOM, synthesize the render tree, and then lay out and render. We can see the layout of the DOM but we can't print the information we want so why do we usually put a script tag at the end of the body tag that's why, or usewindow.onload()/DOMContentLoaded/load;
    Copy the code
Optimization of rendering blocking
Optimizing CSS
  • CSS Media Query

    By making CSS resources available only under certain conditions, they can be loaded for the first time without building the CSSOM tree, and only when certain conditions are met will the browser block rendering and build the CSSOM tree.

    <! Dynamic media queries, which will be calculated when the web page loads. Based on the orientation of the device when the page loads, portrait.cssRendering may or may not be blocked. --> <link href="portrait.css" rel="stylesheet" media="orientation:portrait"> <! It is only applied when printing a web page, so it does not block rendering when the web page is first loaded in the browser. --> <link href="print.css" rel="stylesheet" media="print">
    Copy the code

    Using media queries prevents CSS resources from blocking rendering the first time they are loaded, but no matter what type of CSS resources their download request is ignored, the browser will still download the CSS file first

Optimization of JavaScript
  • async

    HTML parsing is asynchronous to the download of script resources (executed immediately after downloading), but javascript execution is mutually exclusive to GUI threads.

  • defer

    The parsing of HTML is asynchronous to the downloading of script resources, after which the script is executed after all elements have been parsed and before the DOMContentLoaded event is fired.

  • What this diagram doesn’t do with defer is that it executes the scripts in the order they are loaded, which is something to take advantage of
  • Async is an out-of-order master, for which scripts are loaded and executed right next to each other, so no matter what order you declare it, it will be executed as soon as it is loaded. Does not depend on or be dependent on any script.
Other optimization schemes
  • Load part of HTML

    When a server receives a request, it responds with only the initial portion of the HTML, with subsequent HTML content retrieved via AJAX when needed. Since the server only sends part of the HTML file, it takes a lot less work to build the DOM tree, which makes the page feel fast to the user.

    Note that this approach does not work with CSS, and browsers do not allow CSSOM to build only the initial part, otherwise the specific style will not be determined.

  • The compression

    Compress files using GZIP.

  • HTTP cache

    • ETag

      ETag is a delivery validation token that checks for updates to a resource and does not pass any data if the resource has not changed.

      When the browser sends a request, it sends the ETag along with it to the server, which checks the token against the current resource (ETag is usually a fingerprint that has been hashed). If the resource has Not changed, the server returns a 304 Not Modified response, so the browser doesn’t have to download the resource again. Instead, we continue to reuse the cache.

    • Cache-Control

      Cache-control defines the Cache policy, which specifies under what conditions responses can be cached and for how long.

  • Resource preloading

    Pre-fetching is a method that prompts the browser to pre-load a resource that the user may need to fetch.

    • dns-prefetch

      Do DNS resolution ahead of time so you can quickly access another host name later

      <link rel="dns-prefetch" href="other.hostname.com">
      Copy the code
    • prefetch

      Pre-downloaded resources have the lowest priority.

      <link rel="prefetch"  href="/some_other_resource.jpeg">
      Copy the code
    • subresource

      Pre-downloaded resources have the highest priority.

      <link rel="subresource"  href="/some_other_resource.js">
      Copy the code
    • prerender

      Pre-render the page and hide it, then open it up and skip the rendering phase and present it directly to the user (it is recommended to pre-render the page that the user must visit next, otherwise it is not worth the loss).

      <link rel="prerender"  href="//domain.com/next_page.html">
      Copy the code
  • preload

    Speed up download of stylesheets/scripts/fonts/other resources

    <link href="critial.css" rel="stylesheet" />
    <link rel="preload" href="non-critial.css" as="style" />
    <link href="non-critial.css" rel="stylesheet" />
    
    <link rel="preload" href="/ / cdn.staticfile.org/jquery/3.2.1/jquery.min.js" as="script" />
    Copy the code
  • Preload increases the priority of the resource because it indicates that the resource must be used by the page – page first

    Prefetch lowers the priority of the resource because it indicates that the resource is likely to be used by the next page — pre-loaded for the next page

Reflux (Reflow)

(Actions that cause the browser to rerender)

When the size, structure, or attributes of some or all of the elements in the Render Tree change, the process by which the browser rerenders some or all of the document is called reflux.

Operations that cause backflow:

  • Page first render
  • The browser window size changed. Procedure
  • The size or position of the element changed
  • Element content changes (number of words or image size, etc.)
  • Element font size changes
  • Add or removevisibletheDOMThe element
  • The activationCSSPseudo classes (e.g.:hover)
  • Query some properties or call some methods

Some common properties and methods that cause backflow:

  • clientWidth,clientHeight,clientTop,clientLeft
  • offsetWidth,offsetHeight,offsetTop,offsetLeft
  • scrollWidth,scrollHeight,scrollTop,scrollLeft
  • scrollIntoView(),scrollIntoViewIfNeeded()
  • getComputedStyle()
  • getBoundingClientRect()
  • scrollTo()

Author: Waist flower link: juejin.cn/post/684490… The copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.

How to avoid
CSS
  • Avoid the use oftableLayout.
  • As far as possible inDOMThe end of the tree changesclass.
  • Avoid setting multiple inline styles.
  • Apply the animation effect topositionProperties forabsoluteorfixedOn the element of.
  • Avoid the use ofCSSExpressions (e.g.calc()).
JavaScript
  • Avoid frequent manipulation of styles; it is best to rewrite them all at oncestyleProperty, or define the style list asclassAnd change it onceclassProperties.
  • Avoid frequent operationsDOM, create adocumentFragmentApply all of them to itDOM manipulation, and finally add it to the document.
  • You can also set the element firstdisplay: none, and then display it after the operation. Because in thedisplayProperties fornoneOn the element ofDOMThe operation does not cause backflow and redraw.
  • Avoid frequently reading properties that cause backflow/redraw, and if you do need to use them more than once, cache them in a variable.
  • Use absolute positioning on elements with complex animations to keep them out of the document stream, which would otherwise cause frequent backflow of parent elements and subsequent elements.

Redraw (Repaint)

When a change in the style of an element in a page does not affect its position in the document flow (e.g., color, background-color, visibility, etc.), the browser assigns the new style to the element and redraws it, a process called redraw.

Refluxing VS redrawing

Reflux is more expensive than drawing.

  • If a single element is recycled, its parent element and any elements that follow it will also be recycled.
  • Optimize reflux and redraw operations

Performance optimization of HTML writing style

  1. CSS uses separate class names to reduce the nesting of classes and tags and keep them flat

    Reduce recursive rendering in the same way that HTML does not nest meaningless tags

    span {
        color: red;
    }
    /* The browser looks for all spans, then for spans wrapped in a tag, and then for spans wrapped in a tag and wrapped in div, recursively looking for */
    div > a > span {
        color: red;
    }
    Copy the code

Why does manipulating DOM have poor performance?

  1. Manipulating the DOM results in multithreaded concurrency

    Browsers have rendering engines and JS engines. When JS is used to operate DOM (Document.getelementByID), communication between the two engines is required, that is, multi-thread communication, multi-thread concurrent work, resulting in high performance overhead

  2. May cause redrawing and reflow