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 :

  1. 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 .
  2. For each visible node , Find a fit for it CSSOM Rules and apply them .
  3. 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 ------
widthheightmarginpadding
displayborder-widthborderposition
overflowfont-sizevertical-alignmin-height
clientWidthclientHeightclientTopclientLeft
offsetWidthoffsetHeightoffsetTopoffsetLeft
scrollWidthscrollHeightscrollTopscrollLeft
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 :------
colorborder-stylevisibilitybackground
text-decorationbackground-imagebackground-positionbackground-repeat
outline-coloroutlineoutline-styleborder-radius
outline-widthbox-shadowbackground-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, put display 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 it dom, 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

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 !!!

Introduce reflow and redraw (Reflow & Repaint), And how to optimize ? More articles about

  1. Browser reflow and redraw (Reflow & Repaint)

    Write it at the front Before discussing reflow and redraw , We need to know : Browsers use a streaming layout model (Flow Based Layout). The browser will HTML It can be interpreted as DOM, hold CSS It can be interpreted as CSSOM,DOM and CSSOM The merger produces ...

  2. backflow (reflow) And redraw (repaint)

    Recent project schedule is not tight , So I took a look at what I didn't understand after a long time chrome Debugging tools timeline. But unfortunately , Although I know what each item is for , But it's not easy to use . So the point today is not timeline, and ...

  3. Repaint (Repaint) And backflow (Reflow)

    Repaint (Repaint) And backflow (Reflow) 1. Reflow and redraw are just a section of the rendering steps , How does it affect performance ? css It will affect javascrip Execution time results in javascript Script slows down Browser rendering one ...

  4. What is reflow ( rearrangement reflow)? What is redrawing (repaint)? How to reduce backflow 、 Repaint ?

    What is reflow ( rearrangement reflow)? backflow ( rearrangement reflow): Yes DOM Tree rendering , Just modify DOM Or modify the shape and size of the element , It will trigger reflow,reflow When , The browser invalidates the rendered affected part , ...

  5. 【JavaScript】 backflow (reflow) And redraw (repaint)

    Redraw with backflow First of all, understand how the page is rendered : HTML The document is generated after loading DOM Trees ( Include display:none; Elements ): stay DOM On the basis of trees css Style structure generation render Trees ( It doesn't contain display:non ...

  6. HTML Redrawing of the page (repaint) And reflow (reflow)

    Heavy current (Reflow) The layout engine is frame The process of computing graphics . frame It's a rectangle , Has width, height and offset from the parent container .frame Used to display box models (content model), But a content mode ...

  7. 【 note 】web Reflow and redraw and optimize

    Recently, I watched muke.com web Front end performance optimization course , It's about browser reflow (reflow) And Repaint (repaint). I think I may be asked in the future interview, so take notes : The course extends a knowledge point from the two points of reflow and redrawing, that is ...

  8. DOM Of reflow and redraw ( rearrangement 、 Repaint )

    What is? DOM backflow ? When the page is rendered , We are right. HTML When adding, deleting, checking and modifying with simple structure , The browser will be open to all dom Reorder , This is i yes DOM backflow , Serious impact on browser performance DOM Of reflow and redraw : **DOM Back flow of **: When the elements in the page ...

  9. JS Learning notes :( Two ) Reflow and redraw

    Before figuring out the concept of reflow and redraw , We want to clear the browser's rendering process . Parse generation DOM Tree( All nodes are included , Include display:none); according to CSS Object Module(CCSSOM) Computing node ...

  10. 【JS】313- review Reflow and redraw

    Click on the above " Front end self study " Focus on , Learn ~ Original address : I'm not Chen Jigeng segmentfault.com/a/1190000017329980 Backflow and redraw are each of these web Developers often listen ...

Random recommendation

  1. Vmware Fast installation linux virtual machine (SUSE)

    Installation environment :Vmware 11.SUSE11 64 position vmware Fast installation linux The process of virtual machine is relatively simple , Steps are as follows : 1. Click on the file , New virtual machine . 2. Choose a typical installation . 3. Select the virtual machine you want to install in the red box ...

  2. python Common methods of listing in

    s=[1,2,3] s[3]=12# The list length is less than 3 Cannot assign a value to the list len(s)# List length s+s s*5#l The list repeats 5 Time 5 in s# Determine if the element is in the list , return true or false max(s ...

  3. Asp.net The page has no refresh request

    Asp.net The page has no refresh request <%@ Page Language="C#" AutoEventWireup="true" CodeBehind=&qu ...

  4. Memcached Solve the problem of single server failure

    <beitmemcached> <add key="name1" value="server1:port" /> <add key ...

  5. [Effective C++ --025] Consider writing an exception free swap function

    introduction In my last blog , Tells the story of swap function . Original swap It's just STL Part of , And then it becomes the backbone of abnormal security programming , And to deal with the possibility of self assignment . One .swap function Standard library swap Function as follows : namespa ...

  6. Build your own Web service(SOAP piece )

    1. brief introduction This article mainly introduces the use of SOAP To build and access Web service Interface . Web service It's a platform independent , Low coupling , Self contained . Based on programmable web Applications for , Open... Can be used XML( Standards are universal ...

  7. 【 Reprint 】Static The role of keywords

    Original date :2016-07-16 17:53   One    ordinary static keyword 1.   Static global variables Before global variables , Add keywords static, This variable is defined as a static global variable . Let's first take a static global change ...

  8. jquery in substring,substr,split Usage of

    One .substring Method Return to the location of String Object at the specified position . strVariable.substring(start, end) "String Literal" ...

  9. 029 Es Interview section

    1. The outline Es What is it? ? Which business logic is used more ? Es What is analogy database ? For database fields . Table, etc , stay es What is it called in ? Es Of refresh Where to write the data ? Es How does data become indexed and aggregated ? Es Of fl ...

  10. Jmeter The input parameter of the send request must use the encoding format 、Jmeter Send Delete The request may need to use the encoding format

    One of the attribute values here must be encoded before passing parameters , Specific observation can be made through packet capturing analysis :