When a large number of DOM nodes and their styles are involved, sometimes the screen is not smooth, but the browser Alexander is unknown. Therefore, we must be clear about reflow and repaint ).
Based on the style (size, color, location, etc.) of each Dom node, the browser calculates the position and space occupied by each node on the page, this process can be called reflow. When the node location and space are determined, the browser will draw these nodes on the page according to their respective appearances, this process is called repaint );
Trigger reflow
- Dom node addition, modification (content), deletion (reflow + repaint)
- Operate class attributes
- Set the value of the style attribute
- Read certain attributes of an element (offsetleft, offsettop, offsetheight, offsetwidth, scrolltop/left/width/height, clienttop/left/width/height, getcomputedstyle (), currentstyle (in IE ))
It seems that operations on DOM nodes will basically trigger reflow, and triggering reflow will also trigger repaint. Reflow is the key to affecting performance. Therefore, we need to try to reduce the Reflow count as much as possible.
Trigger repaint
As long as the DOM node is modified and its appearance style is affected, the repaint is triggered.
Performance Optimization-Avoid frequent operations on nodes on the document
- Delete the node from the document, modify the node, and place it back in the original position.
- Set the display of the node to none, and then change the display of the node to the original value.
- To create multiple DOM nodes, you can use documentfragment
Performance Optimization-centralized style Modification
- Modify as few attributes as possible on the element style.
- Try to modify the style by modifying the classname
- Set the style value through the csstext attribute
Performance Optimization-cache layout Value
Each time you read the attributes of an element, such as offsetwidth and offsetheight, the browser recalculates the value. If you do not need to obtain the latest status from time to time, you can store the value in the variable.
Performance Optimization-disconnects nodes from document streams
You can set the position of an element to absolute and fixed to separate the element from the DOM tree structure, when rendering, the browser only needs to render the element and the element at the bottom of the element.
. Thinking
There is a long way to go to operate DOM nodes!