Why is DOM manipulation slow? The answer is simple, because DOM operations are cross-threaded
Cross-thread operation
- Browsers are divided into rendering engines and JS engines
- The JS engine cannot manipulate pages, only JS
- Rendering engines cannot manipulate JS, only pages
And when we perform document. The body. The appendChild (div1), JS is how to change the page of the sentence?
- When the browser finds that JS has added a div1 object to the body
- The browser tells the rendering engine to add a new div element to the page as well
- All attributes of the new div element copy the div1 object
This is the part of the browser operation that takes time
The complete process of inserting a new label
- Before DIV1 goes into the page
- All operations to DIV1 are in the JS thread only
- When DIV1 is placed on the page
- The browser will discover the JS intent and inform the render thread to render div1 elements in the page
- After div1 is placed on the page
- An operation to DIV1 might trigger a rerender,
- Div1.id = ‘newId’ may be re-rendered (if the id has CSS styles)
- Div1.title = ‘new'(may be re-rendered), as in:
- We added a fake element to the div. The content is the title of its property, so changing the title will re-render
- If you perform multiple operations on DIV1 in a row, the browser may merge them into one operation
- Here the browser finds that you’ve done two operations on the classList in a short period of time, and by default it merges them into one, so there’s no animation
- If you want animation effect, need to add
test.clientWidth
- The sample
Attribute synchronization
Standard properties
Changes to div1’s standard attributes, such as ID,className,title, etc., are synchronized to the page by the browser
Data – * attributes
Same as above
Nonstandard attribute
After executing the code, our custom non-standard attribute X remains unchanged
So, if you have custom attributes that you want to synchronize to the page, you should prefix them with data-
The Property and the Attribute
- The property attribute
- All properties of div1 in the JS thread, called div1’s property
- The attribute properties
- The attribute that div1 corresponds to in the rendering engine is called an attribute
The difference between:
- Most of the time, property and attribute values with the same name are equal
- But if it’s not a standard property, then they’re only going to be equal at the beginning
- Note that attribute only supports strings
- Property supports strings, booleans, and so on