CSS - redraw reflow

Erdong snail 2021-09-15 09:05:05
css redraw reflow

chrome performance Look at the browser rendering process

First look at a very simple page code

<!Doctye html>
Test dom load.
 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>
<div class='div'>
Test dom load.
<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>
 Copy code 


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) {
 Copy code 


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>
<style type="text/css"> .div { color: blue } </style>
<div class='div'>
Test dom load.
<script type="text/javascript"> var a = 1 + 1; </script>
 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 . ​


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>
<style type="text/css"> .div { color: blue } </style>
<div class='div'>
Test dom load.
<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>
 Copy code 



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>
<style type="text/css"> .div { color: blue } </style>
<div class='div'>
Test dom load.
<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>
 Copy code 



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 】


  • 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()).


  • 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 .

本文为[Erdong snail]所创,转载请带上原文链接,感谢

  1. Contrôle de l'arbre en vue converti en style de table
  2. CSS3 animation flash Effect
  3. Discuter des propriétés de la file d'attente pour l'événement bloc
  4. Node around USModules
  5. Webpack - - Premier aperçu (concept de base)
  6. Mise en œuvre du cadre de base mvvm par JS natif
  7. Calculer les propriétés par rapport aux auditeurs, etc.
  8. Configuration standard dockerfile et docker-composer.yml
  9. Collection de questions d'entrevue HTML
  10. Conteneur, définir la largeur et la hauteur ne répond pas?
  11. Introduction et syntaxe des objets (mise à jour à long terme)
  12. Bubble Mart invests in cat galaxy, which is a vertical e-commerce platform around the quadratic element
  13. Exigences et dépendances dans package-lock.json
  14. Mouvement tridimensionnel de la terre, du ciel et de la lune basé sur three.js
  15. Compréhension et analyse de l'objet de base JS
  16. Simple use of status data management (context, mobx, Redux)
  17. Simulated drumming
  18. Array method
  19. Performance optimization issue 03 - HTTP request optimization
  20. Vue learning -- watch listener
  21. Learn more about nexttick in Vue
  22. Talk about some moves used by vue3.0 in the project - External skill chapter (I)
  23. JavaScript genrator generator
  24. La dernière réponse à l'entrevue de développement Android, l'hiver froid de l'industrie
  25. Maserati's motorcycle has less than 10 in the world. It is definitely a work of art
  26. 2021 partage des questions du dernier examen écrit d'entrevue Android, pas d'accord
  27. Programmation asynchrone Java scirp, développement frontal de base
  28. 2021 dernier examen écrit d'entrevue Android, écrit trop bien
  29. Quels aspects doivent être pris en considération dans le tableau principal du distributeur libre - service?
  30. He inherited his mother's hundreds of millions of property for his boyfriend to squander. Unexpectedly, he was ruthlessly abandoned when he had 100 yuan left
  31. The fuel cost is half less than that of fuel vehicles at the same level. Is it really cheap to use song Pro DM?
  32. Le dernier résumé de l'expérience d'entrevue d'embauche de l'école Android de l'usine est nécessaire pour l'usine
  33. Le dernier dictionnaire avancé de programmeurs d'usine, l'expérience d'entrevue d'embauche de l'Agence de développement Android
  34. La dernière collection d'entrevues Android Golden nine Silver ten
  35. L'expérience d'entrevue de l'Ingénieur d'algorithme de saut d'octets, 2 mois d'entrevue Tencent, station B, Netease et ainsi de suite sur 11 entreprises résumé!
  36. La dernière collection d'entrevues d'Android Golden nine Silver ten recommande un projet github
  37. Yuan Li's recent situation revealed that he was obsessed with public welfare, dressed simply and fearless, grew fat, and married an 11-year-old husband
  38. Initial experience of template tool plop of [front end Engineering]
  39. Dernière question d'entrevue avancée et réponse d'Alibaba Android, Alibaba P8 vous apprendra en personne
  40. Partage des dernières questions d'entrevue pour Android haute fréquence, Introduction aux compétences d'entrevue pour le développement d'Android
  41. Partager les dernières questions d'entrevue Android haute fréquence avec quelques conseils
  42. About JavaScript modules
  43. Iteratable object and class arrays
  44. Function realization of Vue elementui exporting excel form
  45. Use canvas to realize a small screenshot function
  46. Object oriented programming (2)
  47. Several common value transfer methods between Vue components
  48. Démarrer avec le serveur de base zéro: Hello World
  49. J'a I construit un escalier pour aller sur la lune, combien de façons puis - je poursuivre la sœur Chang'e?
  50. CSS implémente la fonction d'expansion et d'arrimage du Texte multiligne
  51. Varlet CLI | vue3 Component Library Quick Prototyping Tool
  52. Belle vue sur les trois rivières Xiapu
  53. La partie Web qui déploie SharePoint ajoute son propre module de fonctionnalité
  54. React Native (mise à jour à long terme)
  55. La conception et le codage de l'arbre binaire requis pour chaque entrevue d'embauche de la société Java millet;
  56. 10 jours pour obtenir l'offre d'emploi Android d'Alibaba, entrevue Android
  57. A remporté avec succès Byte, Tencent, Pulse offer, 7 ans Java une expérience d'entrevue de baise,
  58. 10大前端常用算法,web应用与开发
  59. Nginx - minimum configuration! You deserve it
  60. Les questions d'entrevue couramment utilisées pour le cadre Java sont - elles prometteuses pour le développement Java?