Preface
Reflow and redraw are very important knowledge points for the front end , We not only need to know what reflow and redraw are , You also need to know how to optimize . A page from loading to completion , The first is to build DOM Trees , And then according to DOM The geometric attributes of nodes form render Trees ( Render tree ), When the rendering tree is built , The page is based on DOM The tree began to lay out , The rendering tree also renders these nodes according to the set style . In the process , Reflux and DOM Trees , Rendering tree , Redrawing is related to rendering trees .
If this article helps you ,️ Focus on + give the thumbs-up ️ Encourage the author , The official account is the first , Focus on Front end Nanjiu
The first time to get the latest articles ~
Page rendering process
- analysis HTML structure DOM Tree
- analysis CSS structure CSSOM Tree
- Build the render tree (Render Tree), The rendering tree contains only the nodes needed to render the web page
To build a rendering tree , The browser basically completes the following work :
- from DOM The root node of the tree begins traversing each visible node .
- Some nodes are not visible ( For example, script tags 、 Meta tags, etc ), Because they are not reflected in the rendered output , So it will be ignored .
- Some nodes pass through CSS hide ( for example display: none), Therefore, it will also be ignored in the rendering tree .
- For each visible node , Find a fit for it CSSOM Rules and apply them .
- Launch visible nodes , Together with its content and calculation style .
Note: Please note that visibility: hidden
And display: none
It's different . The former hides elements , But the elements still occupy the layout space ( Render it as an empty box ), While the latter (display: none
) Completely remove elements from the rendering tree , The element is neither visible , It's not part of the layout .
The final output rendering contains all the visible content on the screen and its style information . With the rendering tree , We can enter “ Layout ” Stage .
- The layout calculates each DOM The exact location and size of the object
- Rendering ( draw , synthesis ), Use the final render tree to render pixels to the screen
For the process of page rendering, see my previous article : Super detailed explanation of the page loading process , Here we focus on Repaint And backflow On .
What is reflow (Reflow) And redraw (Repaint)?
backflow (Reflow)
When rendering trees render tree
Part of ( Or all ) Because of the size of the element , Layout , Changes such as hiding need to be rebuilt . This is called a backflow (reflow). Each page needs at least one reflow , The first time the page is loaded , At this time, there is bound to be backflow , Because to build render tree
. When it comes back , Browsers invalidate the affected parts of the rendering tree , And reconstruct this part of the rendering tree , When the reflux is complete , The browser will redraw the affected part to the screen , The process is called Repaint .
Simply speaking , Reflow is to calculate the exact position and size of elements in the device and redraw
The cost of reflow is much greater than redrawing . And reflow will inevitably cause redrawing , But redrawing does not necessarily cause backflow .
Repaint (Repaint)
When rendering trees render tree
Some elements in the need to update the style , But these style attributes only change the appearance of the element , style , It doesn't affect the layout , such as background-color
. It is called Repaint (repaint).
Simply speaking , Redrawing is to convert render tree nodes into actual pixels on the screen , It does not involve the calculation of the position and size of the rearrangement stage
Why not recommend frequent operation DOM?
We all know the operation DOM In fact, it is very performance consuming , So we Not only to avoid operation DOM, Also reduce access DOM The number of times .
Because in the browser ,DOM
and JS
The implementation of the , It is not done in the same engine .DOM
It belongs to Rendering engine
Middle East ⻄,⽽JS
⼜ yes JS engine
Middle East ⻄. When we go through JS
operation DOM
When , It involves the communication between two threads , So it's bound to bring ⼀ Some performance losses . operation DOM frequency ⼀ many , Which is the same thing as ⼀ Straight ahead ⾏ Communication between threads , And the operating DOM There may also be a case of redraw backflow , So that leads to performance problems .
hold DOM and JavaScript Think of each as an island , They are connected by toll bridges .
--《 High performance JavaScript》
When will backflow occur (Reflow) And redraw (Repaint)?
Operation leading to backflow :
- Page first render ( Unavoidable and costly )
- Browser window size changes (resize event )
- A change in the size or position of an element ( Margin 、 Wide and high 、 Borders, etc )
- Element content changes ( The number of words or the size of pictures and so on )
- Element font size changes (font-size)
- Add or remove so Of
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 :
Cause reflow properties and methods | -- | -- | -- |
---|---|---|---|
width | height | margin | padding |
display | border-width | border | position |
overflow | font-size | vertical-align | min-height |
clientWidth | clientHeight | clientTop | clientLeft |
offsetWidth | offsetHeight | offsetTop | offsetLeft |
scrollWidth | scrollHeight | scrollTop | scrollLeft |
scrollIntoView() | scrollTo() | getComputedStyle() | |
getBoundingClientRect() | scrollIntoViewIfNeeded() |
Why does getting some properties or calling methods also lead to backflow ?
Because the above properties and methods need to return the latest layout information , Therefore, the browser has to trigger reflow redrawing to return the correct value .
Attributes that cause redrawing
attribute : | -- | -- | -- |
---|---|---|---|
color | border-style | visibility | background |
text-decoration | background-image | background-position | background-repeat |
outline-color | outline | outline-style | border-radius |
outline-width | box-shadow | background-size |
Specific information can be found on this website CSS Triggers
Browser optimization mechanism
Each rearrangement results in additional computational overhead , Therefore, most browsers optimize the rearrangement process by queueing changes and executing them in batches . The browser queues up the changes , Until some time has passed or the operation has reached a threshold , Before batch modification and emptying the queue . however , When obtaining layout information , The queue will be forced to be refreshed , Such as when you access the following properties or use the following methods :
clientTop、clientLeft、clientWidth、clientHeight
offsetTop、offsetLeft、offsetWidth、offsetHeight
scrollTop、scrollLeft、scrollWidth、scrollHeight
getComputedStyle()
getBoundingClientRect
You can visit this website for details :paulirish
Both the above properties and methods need to return the latest layout information , So the browser has to clear the queue , Triggers a backflow redraw to return the correct value . therefore , While we're modifying the style , It is best to avoid using the properties listed above , They all refresh the render queue .
How to reduce backflow (Reflow) And redraw (Repaint)?( Optimize )
Merging is good for DOM
Modification of styles , use css class
To modify the
const el = document.querySelector('.box')
el.style.margin = '5px'
el.style.borderRadius = '12px'
el.style.boxShadow = '1px 3px 4px #ccc'
It is recommended to use css class
.update{
margin: 5px;
border-dadius: 12px;
box-shadow: 1px 3px 4px #ccc
}
const el = document.querySelector('.box')
el.classList.add('update')
If necessary DOM Multiple visits , Try to cache this with local variables DOM
Avoid using table Layout , It could be very ⼩ Of ⼀ individual ⼩ The change will cause the whole thing table relayout
CSS The selector matches from right to left , Avoid excessive node hierarchy
DOM Offline processing , Reduce the number of reflow redraws
off-line DOM Does not belong to the present DOM Any part of a tree , This means that we are offline DOM Processing will not cause page backflow and redrawing .
- Use
display: none
, We mentioned above (display: none
) Completely remove elements from the rendering tree , The element is neither visible , It's not part of the layout , After that, at the time DOM The operation on does not trigger reflow and redraw , After the operation, putdisplay
Property to display , Will only trigger this reflow and redraw .
remind :visibility : hidden
The elements of have an effect only on redrawing , It doesn't affect the rearrangement .
- adopt documentFragment Create a
dom
Document fragment , Batch operation on itdom
, After the operation , Add it to the document , This will only trigger a rearrangement .
const el = document.querySelector('.box')
const fruits = ['front', 'nanjiu', 'study', 'code'];
const fragment = document.createDocumentFragment();
fruits.forEach(item => {
const li = document.createElement('li');
li.innerHTML = item;
fragment.appendChild(li);
});
el.appendChild(fragment);
- Clone node , Replace the original node after modification
const el = document.querySelector('.box')
const fruits = ['front', 'nanjiu', 'study', 'code'];
const cloneEl = el.cloneNode(true)
fruits.forEach(item => {
const li = document.createElement('li');
li.innerHTML = item;
cloneEl.appendChild(li);
});
el.parentElement.replaceChild(cloneEl,el)
DOM Break away from normal document flow
Use absoult
or fixed
Take the element out of the ordinary document stream , Using absolute positioning makes that element a separate element in the rendering tree body
A child element of , Rearrangement costs less , It won't affect other nodes too much .
CSS3 Hardware acceleration (GPU Speed up )
Use css3 Hardware acceleration , It can make transform、opacity、filters
These animations do not cause backflow redraw . But for other properties of animation , such as background-color
these , It still causes backflow to redraw , But it can still improve the performance of these animations .
Common trigger for hardware acceleration css attribute :
- transform
- opacity
- filters
- Will-change
Set the node to layer
Layers can block ⽌ Rendering of this node ⾏ To affect other nodes .⽐ As for the video The label is , Browser meeting ⾃ Turn the node into a layer .
Recommended reading
- Promise、Generator、Async What's the difference? ?
- 【Vue Source code learning 】 Rely on collection
- 【Vue Source code learning 】 Exploration of the principle of response
- JS Causes and solutions of unreliable timer execution
- From how to use to how to implement a Promise
- Super detailed explanation of the page loading process
The original address Click here , Welcome everyone to follow the official account 「 Front end Nanjiu 」, Reply to the group , Pull you into the front-end communication group to learn together , Reply to information , Get front-end e-books and learning videos ~.
I'm Nan Jiu , See you next time !!!