What is a document fragment?
DocumentFragment interface, a minimal document object with no parent object. It is used as a lightweight version of Document that stores a Document structure composed of nodes, just like a standard Document.
What does it do
Compared with Document, the biggest difference is that DocumentFragment is not part of the real DOM tree, and its change will not trigger the DOM tree re-rendering, and will not cause performance problems.
How to use A DocumentFragment
let fragement = document.createDocumentFragment()
console.log(fragement.nodeName)//#document-fragment
console.log(fragement.nodeType)/ / 11
console.log(fragement.nodeValue)//null
console.log(fragement.parentNode)//null
Copy the code
Normally, we add elements to dom elements using the Node.appendChild and Node.insertBefore methods. Each node is inserted into the document separately, resulting in multiple re-renders and page backflow, which can be costly in performance and affect the user experience.
What does a DocumentFragment solve?
Using A DocumentFragment can solve the problem of backflow caused by direct manipulation of the DOM, because all nodes are inserted into the document at once, and this operation only takes place in a single re-render operation. For example, we want to add five LI nodes to ul. The difference is like this:
let app = document.querySelector('.app')
for(let i = 0; i<5; i++){let div = document.createElement('li')
div.setAttribute('class'.'item')
div.innerText = 6666
app.appendChild(div)
}
Copy the code
Use The DocumentFragment to add once and return once:
let app = document.querySelector('.app')
let fragement = document.createDocumentFragment()
for(let i = 0; i<5; i++){let div = document.createElement('li')
div.setAttribute('class'.'item')
div.innerText = 6666
fragement.appendChild(div)
}
app.appendChild(fragement)
Copy the code
Conclusion: DocumentFragment nodes do not belong to the document tree, but exist in memory and not in the DOM. Therefore, inserting child elements into document fragments will not cause page backflow. Therefore, using DocumentFragment can play a role of performance optimization.