CSS - redraw reflow

Erdong snail 2021-09-15 09:05:05

chrome performance Look at the browser rendering process

First look at a very simple page code

<!Doctye html>
<html>
<head>
</head>
<body>
<div>
Test dom load.
</div>
</body>
</html>
 Copy code 

Then open the chrome performence View the rendering process of the page : image.png

  • Send Request : Triggered when a network request is sent
  • Receive Response: Triggered when the response header message arrives
  • Receive Data: The requested response data arrives at the event , If the response data is large ( unpacking ), This event may be triggered multiple times
  • Finish Loading: Network request completion event
  • Parse HTML: Browser execution HTML analysis
  • Update Layer Tree : Update the layer tree .
  • Paint: After determining the size and location of the nodes on the render tree , You can doodle the nodes (paint)
  • Composite Layers: Composite layer , When the node graffiti on the rendering tree is finished , A bitmap is generated (bitmap), The browser changes this bitmap from CPU Transferred to the GPU

Parse Html(without css and js)


<!Doctye html>
<html>
<head>
</head>
<body>
<div class='div'>
Test dom load.
</div>
<script type="text/javascript"> console.log('resolve body JavaScript'); window.addEventListener('load',function(){ console.log('window load'); }) document.addEventListener('readystatechange',function(){ console.log('document ' + document.readyState); }) document.addEventListener('DOMContentLoaded',function(){ console.log('document DOMContentLoaded'); }) //document No, load event ?? document.addEventListener('load',function(){ console.log('document load'); }) </script>
</body>
</html>
 Copy code 

image.png

Then let's take a look at the things inside from left to right according to the timeline ( But first, let me say , What do you think of this picture , The following content is the call of the above content , Here, that is, the contents with text description in the figure above are in ParseHtml What is called in the cycle of ):

readystatechange( first )

When you say this, you need to say an event DOM readystatechange, readyState Property describes the loading status of the document , During the whole loading process document.readyState It's going to change , Every change triggers readystatechange event . ​

readyState There are the following states :

  • loading load document Still loading .
  • interactive The interactive document has finished loading , The document has been parsed , But things like images , Sub resources like stylesheets and frames are still loading .
  • complete complete DOM The document and all sub resources have finished loading . State means load The event is about to be triggered .

So what step does the event here perform ?

What's going on here is interactive. Because this event is followed by DOMContentLoaded event , And if you visit this page in person , stay parseHtml There's another time ahead readystatechange, It should be loading .

DOMContentLoaded ( structure DOM Tree success )

DOM Triggered when tree rendering is complete DOMContentLoaded event , At this time, external resources may still be loading . It means DOM Tree loading complete .

Recalculate Style( structure CSSOM Trees )

From the literal meaning of the text, that is to recalculate the style . Why Re-caculate Style Well ? This is because the browser itself has User Agent StyleSheet, So the final style is that our style code style overrides the user agent's default style / Recalculated . Here is also building CSSOM Trees .

readystatechange( the second )

It can be seen from the first event that what is performed here is complete, Represents the DOM Trees and CSSOM Trees have been formed and merged into Render Trees . At this point, all resources on the page have been loaded . In fact, from the back load Events can also be seen

load event

When all resources are loaded, it will trigger window Of load event .

pageshow event

When a session history is executed, the page display will be triggered (pageshow) event .( This includes stepping back / Forward button operation , At the same time load Triggered when the page is initialized after the event is triggered ).

The following example will be printed on the console / Back button and load Caused after the event is triggered pageshow event :

window.addEventListener('pageshow', function(event) {
console.log('pageshow:');
console.log(event);
});
Layout
 Copy code 

Layout

Render the nodes on the tree , According to its height , Width , Location , Generate boxes for nodes (layout). Add a box model to the element . In the picture above, there are two layout, The difference between the two is Nodes That Need Layout 1/5 of 5 there 5 The representative should be... On the page 5 individual node( Text content is a text node ), But for this 1, There is still no clear explanation , But it doesn't make much difference , After all, it still belongs to layout. ​

Actually, I see here : Let's think about ParseHtml What did you do : structure DOM Trees -> structure CSSOM Trees -> structure Render Trees -> Layout layout

Parse Html(with css and js)

<!Doctye html>
<html>
<head>
<style type="text/css"> .div { color: blue } </style>
</head>
<body>
<div class='div'>
Test dom load.
</div>
<script type="text/javascript"> var a = 1 + 1; </script>
</body>
</html>
 Copy code 

image.png Here is only the difference from the above picture : ​

The first is more than two yellow js Related content , A place called Evaluate Script( load js), The other is Compile Script(js Precompiling , You can view articles , It's already right here js The file executed ). ​

The second difference is from the second readystatechange From the incident to layout It's gone ParseHtml It's done internally . Here I simply did a test , Only css perhaps js In the presence of , The same result as now , Because css perhaps js Blocking the rendering process of the entire page , because js and css It is possible to set the style of labels , So it's affecting layout Implementation .

Test reflow and redraw

The timer will be used below , Because of the modern browser team, modern browsers optimize frequent reflow or redraw operations , There may be batch processing , No effect . ​

backflow

When Render Tree The size of some or all of the elements in 、 structure 、 Or when some properties change , The process of the browser re rendering part or all of the document is called reflow .


<!Doctye html>
<html>
<head>
<style type="text/css"> .div { color: blue } </style>
</head>
<body>
<div class='div'>
Test dom load.
</div>
<script type="text/javascript"> var a = 1 + 1; document.getElementsByTagName('div')[0].style.marginTop = '20px' setTimeout(() => { document.getElementsByTagName('div')[0].style.marginTop = '40px' }, 1000) </script>
</body>
</html>
 Copy code 

image.png

Repaint

When an element style change in a page does not affect its position in the document flow ( for example :color、background-color、visibility etc. ), The browser assigns the new style to the element and redraws it , This process is called redrawing . ​


<!Doctye html>
<html>
<head>
<style type="text/css"> .div { color: blue } </style>
</head>
<body>
<div class='div'>
Test dom load.
</div>
<script type="text/javascript"> var a = 1 + 1; document.getElementsByTagName('div')[0].style.color = 'green' setTimeout(() => { document.getElementsByTagName('div')[0].style.color = 'red' }, 1000) </script>
</body>
</html>
 Copy code 

image.png

Conclusion

Reflux causes :Update Layer Tree -》layout -》 Paint -》Composite Layers Redrawing results in :Update Layer Tree -》Paint -》Composite Layers ​

Reflow causes redrawing , Redrawing does not cause reflow .

Operation causing backflow

juejin.cn/post/684490… Operation leading to backflow :

  • Page first render
  • Browser window size changes
  • A change in the size or position of an element
  • Element content changes ( The number of words or the size of pictures and so on )
  • Element font size changes
  • Add or remove visible DOM Elements
  • Activate CSS pseudo-classes ( for example ::hover)
  • Query some properties or call some methods

Some common properties and methods that lead to backflow : clientWidth、clientHeight、clientTop、clientLeft offsetWidth、offsetHeight、offsetTop、offsetLeft scrollWidth、scrollHeight、scrollTop、scrollLeft scrollIntoView()、scrollIntoViewIfNeeded() getComputedStyle() getBoundingClientRect() scrollTo()

How to avoid

The following sources :juejin.cn/post/684490… 【 Nuggets - Kidney flower 】

CSS

  • Avoid using table Layout .
  • As far as possible DOM The end of the tree changes class.
  • Avoid multiple inline styles .
  • Apply animation effects to position The attribute is absolute or fixed Elements on .
  • Avoid using CSS expression ( for example :calc()).

JavaScript

  • Avoid frequent operation styles , It's better to rewrite it once style attribute , Or define the style list as class And change it all at once class attribute .
  • Avoid frequent operation DOM, Create a documentFragment, Apply all... To it DOM operation , Finally add it to the document .
  • You can also set the element first display: none, Show it after the operation . Because in display The attribute is none On the elements of DOM Operation will not cause reflow and redraw .
  • Avoid backflow caused by frequent reads / Redrawn properties , If it does need to be used many times , Just cache it with a variable .
  • Use absolute positioning for elements with complex animation , Take it out of the document stream , Otherwise, it will cause frequent reflow of parent elements and subsequent elements .

Please bring the original link to reprint ,thank
Similar articles

2021-09-15

2021-09-15

2021-09-15