Browser rendering principles, redraw and reflow

What happens when you enter a URL into the browser’s input field to render the page?

1. The browser sends a request to the server.

  1. Including DNS resolution, HTTP, HTTPS, and TCP.
  2. The server returns the source code to the client in the indecx.html page.
  3. The browser assigns a thread to parse and render the code “top down, left to right.”
  4. Browsers are multithreaded, page rendering is single-threaded (JS is single-threaded)

2. Parse down when rendering encounters styles (CSS)

1. Inline styles

<body> <h1 style = "color:white; background-color:blue"> This is a line of Text. </h1> <h1 style="color:red;" "> <p style="font-size:14px; color:green;" > Styles set directly in HTML tags </p> </body>Copy the code
  1. Use the style property to introduce CSS styles.
  2. Features:
  • (1) Inline styles are placed in HTML elements in the code.
  • (2) When using inline styles, styles only affect the elements you select.
  • (3) Inline styles have no selectors

2. Style is embedded

<! DOCTYPE> < HTML > <head> <meta charset=" UTF-8 "/> <title> internal style sheet </title> <! <style type="text/ CSS "> div{background: green; } < / style > < / head > < body > < div > I am a div < / div > < / body > < / HTML >Copy the code
  1. Is placed in the header of a web page written with the style tag < styleType =”text/ CSS “>.

  2. Parse normally from top to bottom (parse and then continue parsing DOM deconstruction)

  3. Synchronous loading.

  4. Optimization: In real projects, if CSS style code is not very high (or mobile projects), we should use inline to reduce HTTP resource requests and improve page rendering speed. You can first write the first screen style embedded, other write link load.

  5. Embedded CSS only works on the current page. Because the CSS code is in an HTML file, it makes the code more centralized, which is often advantageous when writing template web pages. Because the person looking at the template code can see the HTML structure and CSS styles at a glance. Because the embedded CSS is only valid for the current page, this can lead to code redundancy and maintenance problems when multiple pages need to introduce the same CSS code.

3. Link Import external style resources (link style)

<head>
<link rel="stylesheet" type="text/css" href="css.css">
</head>
<body>
    	<h1>
    		This is a line of Text.
    	</h1>
</body>

Copy the code
  1. If a Link is encountered during page loading, the browser will create a new thread to load the corresponding resource from the server (without blocking the main thread rendering).
  2. Asynchronous loading.
  3. This is the most common and recommended way to introduce CSS. In this way, all the CSS code exists in a single CSS file, so it is very maintainable. All CSS code exists only in the CSS file. The CSS file is introduced when the page is loaded for the first time, and then only the HTML file is loaded when the page is switched.

4. @ import import


<head>
<style>
	@import url("css.css");
</style>
</head>
<body>
    	<h1>
    		This is a line of Text.
    	</h1>
</body>

Copy the code
  1. Instead of opening a new thread to load the resource file, let the main thread load and fetch it, which prevents the DOM deconstruction from continuing rendering.
  2. The DOM deconstruction will continue rendering only after the external styles are imported and parsed
  3. It’s synchronous programming (so it’s better to use an asynchronous link). If you specify whose style to import first, then you can use @import.
  4. Both are external references to CSS, but there are some differences:
  • Difference 1: Link is an XHTML tag that can define other transactions, such as RSS, in addition to loading CSS. @import belongs to CSS and can only load CSS.

  • Difference 2: When link references CSS, the page is loaded at the same time; @import requires the page to be loaded after the page is fully loaded.

  • Difference 3: Link is an XHTML tag, no compatibility issues; @import was introduced in CSS2.1 and is not supported by older browsers.

  • Difference 4: Link supports using Javascript to control the DOM to change styles; @import is not supported.

Priority of several ways

A: Inline style > Internal style > External style (the last two are the nearest rule)

Another aspect: selector priority

Priority: ID selector > Class selector > tag selector

When is it better to use which method?

Number of network resource requests (maximum number of CONCURRENT HTTP requests)?

  1. Most browsers stay around six. (When there are more than six, the rest will have to wait in line)
  2. Optimization: In order to avoid concurrent on-line, some resources have to be loaded lazily and the page rendering speed is slow, we should minimize the number of HTTP requests. (Reduce the number of HTTP requests)

3. Js encountered during page loading (there will be code to manipulate DOM in JS)

(1) Default

  1. The main thread will fetch JS resources from the server, parse and load js resources, and then continue to render DOM structure after loading.
Classic question: Why write CSS at the top and Script at the bottom of a structure?
=> Link at the top: To make the CSS load back faster => script at the bottom is to get the DOM element or not to block DOM rendering.Copy the code
  1. The current browser scanning mechanism:

If a script needs to be loaded and rendered synchronously, the browser will continue to scan the code while rendering JS. If it finds some asynchronous resource code, it will start loading.

Because it is possible to manipulate the style of elements in JS, the JS code will not be executed until the CSS it sent has been loaded and rendered, even in the case of asynchronous resource requests.

(2) Want to put JS like CSS, using a separate thread processing

You can set defer or async: both fetch resources asynchronously (without blocking DOM rendering)

=> defer

If defer is set: you can follow the original loading order and render the JS in that order

=> async

If async is set to unordered (first fetch, first execute)

4. DOMContentLoaded and load events

DOMContentLoaded event

  1. This event is emitted when the DOM structure is loaded
  2. This event is emitted when the DOM tree is available and the JS is loaded

The load event

  1. This is triggered when all resources have been loaded
  2. This includes waiting for images and other resources to load before triggering this.

5. In jQuery
( f u n c t i o n ( ) ) or Or (function ())
(document)

  1. When the DOM structure is loaded, the code in the function is executed.
  2. The principle is to apply the DOMContentLoaded event, but it is incompatible with lower version browsing.
  3. You can use the onReadyStatechange event instead, where you listen for the document.readyState value, indicating that the DOM structure has been loaded for complete.

Refluxing and repainting

The process of browser rendering

  1. Parse HTML, generate DOM tree, parse CSS, generate CSSOM tree
  2. Combine DOM Tree and CSSOM Tree to generate Render Tree
  3. Layout: Calculate their exact position and size within the device viewport based on the generated render tree. This stage of calculation is called backflow
  4. Painting(repainting): Get absolute pixels of nodes based on the rendered tree and geometry information from backflow
  5. Display: Send the pixel to the GPU and Display it on the page

Layout (return) :

  1. Definition: A change in the size or position of an element (when the page layout and geometry information changes) triggers a relayout, causing the render tree to recalculate the layout and render.
  2. For example:
    • Add or remove visible DOM elements;
    • The position of the element changes;
    • The size of the element changes;
    • Content changes (e.g. text changes or an image is replaced by another image of a different size);
    • When the page is first rendered (which is inevitable);
    • Because backflow calculates the location and size of elements based on the viewport size, browser window size changes can also trigger backflow….

Painting (redraw) :

  1. Definition: Element style changes (but width, height, size, position, etc.)
  2. Example: such as outline, visibility, color, background-color, etc

Note: Backflow must trigger redraw, and redraw does not necessarily backflow

There must be a backflow and redraw between entering the URL and seeing the page

Front-end performance optimization: Avoid DOM backflow

Abandoning the era of traditional dom manipulation, vUE/React started the data impact view mode

mvvm / mvc / virtual dom / dom diff ......
Copy the code

Separate read and write operations (modern browsers have a render queue mechanism)

OffsetTop, offsetLeft, offsetWidth, offsetHeight, clientTop, clientLeft, clientWidth, clientHeight ScrollTop, scrollLeft, scrollWidth, scrollHeight, getComputedStyle, currentStyle.... The render queue is refreshedCopy the code

Style set changes

div.style.cssText = 'width:20px; height:20px; ' div.className = 'box'; Let nav = document.getelementById ('nav'); let nav = document.getelementById ('nav'); Nav.style. height = '100px' // Trigger 2 times, nav.style.width = '100px'; console.log(nav.clientWidth) nav.style.height = '100px'Copy the code

Cache layout information

div.style.left = div.offsetLeft + 1 + 'px'; div.style.top = div.offsetTop + 1 + 'px'; Var curLeft = div. OffsetLeft; var curTop = div.offsetTop; div.style.left = curLeft + 1 + 'px'; div.style.top = curTop + 1 + 'px';Copy the code

Element batch modification

  1. Document fragment: createDocumentFragment
//10 times for (let I =0; i <10 ; i++){ let span = document.createElement('span'); Nav. SppendChild (span)} / / 1 time let frag = document. CreateDocumentFragment (); for (let i =0; i <10 ; i++){ let span = document.createElement('span'); AppendChild (span)} nav.sppendChild(frag) // let STR = ' '; for (let i =0; i <10 ; i++){ str + = `<span></span>`; } nacBox.innerHTML = strCopy the code

Animation applied to elements with position property absolute or fixed (out of document flow)

CSS3 Hardware acceleration (GPU acceleration)

  1. Rather than thinking about how to reduce backflow redraw, we’d like to see no backflow redraw at all;
  2. transform \ opacity \ filters … These properties trigger hardware acceleration and do not cause backflow and redraw……
  3. Possible pitfalls: too much use can take up a lot of memory, consume a lot of performance, sometimes cause font blur, etc

Sacrifice smoothness for speed

  1. Move an animation 1 pixel at a time, but if the animation is using 100% CPU, the animation will look jumpy because the browser is struggling with update backflow.
  2. Moving 3 pixels at a time may seem low in smoothness, but it won’t cause the CPU to shake on a slower machine

Avoid table layouts and javascript expressions using CSS