search
HomeWeb Front-endJS TutorialDetailed explanation of Repaint and Reflow usage in JavaScript_Basic knowledge

Have you often heard from seniors or some front-end seniors that you cannot use CSS wildcard *, CSS selector stacking cannot exceed three levels, use class selectors as much as possible in CSS, use tables less when writing HTML, and the structure should be as simple as possible - DOM tree Waiting for these advices, I have roughly known that using wildcards or too many levels of CSS selectors may reduce performance. As for why I don’t use table tags, I have always been confused, so I just followed that, but I After getting to know Repain and Reflow, it turns out that these really can't be used too much. ok, I hope this article is helpful to you!

1. What is Repaint/Reflow?

Okay, let’s take a picture first: the general workflow of browser parsing

2015727180703820.png (600×196)

This picture should be easy to understand and can be summarized into four steps:

1. Parse HTML to build a DOM tree: The rendering engine starts to parse the HTML document and convert the html tags in the tree or tags generated by js to DOM nodes, which is called -- content tree.
2. Build a rendering tree: parse the CSS (including external CSS files and style elements as well as styles generated by js), calculate the style of the node based on the CSS selector, and create another tree - the rendering tree.
3. Layout rendering tree: Called recursively from the root node, calculate the size, position, etc. of each element, and give each node the precise coordinates where it should appear on the screen.
4. Draw the rendering tree: Traverse the rendering tree, and each node will be drawn using the UI backend layer.

Okay, we can see that Repain and Reflow appear in the third and fourth steps respectively. Therefore we give the following definition:

Each element in the DOM structure has its own box (model), which requires the browser to calculate according to various styles (browser, developer-defined, etc.) and place the elements in it according to the calculation results This process is called reflow; when the position, size and other attributes of various boxes, such as color, font size, etc., are determined, the browser draws these elements according to their respective characteristics. , so the content of the page appears, this process is called repaint.
It can be seen that these two things are very important for the browser to render the page, and they will affect the performance. Therefore, we need to understand some common operations that will cause repaint and reflow, and they should be minimized to improve the rendering speed.

2. Some operations that cause Repain and Reflow

The cost of Reflow is much higher than that of Repaint. Each node in the DOM Tree will have a reflow method. The reflow of a node is likely to lead to the reflow of child nodes, or even parent nodes and sibling nodes. It may be okay on some high-performance computers, but if reflow occurs on a mobile phone, the process is very painful and power-consuming.
Therefore, the following actions are likely to be relatively costly.

  • When you add, delete, or modify DOM nodes, it will cause Reflow or Repaint.
  • When you move the position of the DOM or create an animation.
  • When you modify CSS styles.
  • When you resize the window (the mobile version does not have this problem), or when scrolling.
  • When you modify the default font of a web page.

Note: display:none will trigger reflow, while visibility:hidden will only trigger repaint because no position change is found.
3. How to optimize?

Reflow is inevitable, and the impact of Reflow on performance can only be minimized. Here are some suggestions:

Don’t modify the DOM style one by one. Instead of doing this, it is better to pre-define the css class and then modify the DOM className:

 // 不好的写法
  var left = 10,
  top = 10;
  el.style.left = left + "px";
  el.style.top = top + "px";
  // 推荐写法
  el.className += " theclassname";

Modify the DOM after taking it offline. Such as:
a> Use the documentFragment object to operate the DOM in memory.
b> First give the DOM display:none (one repaint), and then you can change it however you want. For example, modify it 100 times and then display it again.
c> Clone a DOM node into the memory, and then change it however you want. After the change is completed, exchange it with the online one.

Don’t put the attribute values ​​of DOM nodes in a loop as variables in the loop. Otherwise this will result in a large number of reads and writes of the node's attributes.

Modify lower-level DOM nodes as much as possible. Of course, changing lower-level DOM nodes may cause a large area of ​​reflow, but the impact may also be small.

If you use fixed or absoult position for animated HTML elements, modifying their CSS will greatly reduce reflow.

Never use table layout. Because a small change may cause the entire table to be rearranged.

After understanding these, are you more interested in the principles of browsers? OK, I will update the article about browser principles later, or you can search others first, because I think it is really important to understand the principles of browsers, which can help us write websites with better performance.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.