Here’s the official description:

A DocumentFragment represents a minimal document object that has no parent file. It is used as a lightweight version of Document to store formatted or poorly formatted XML fragments. The biggest difference is that the DocumentFragment is not part of the real DOM tree, and its changes do not cause reflow of the DOM tree or performance issues.

The DocumentFragment interface represents a portion (or segment) of a document. Rather, it represents one or more adjacent Document nodes and all of their descendants. The DocumentFragment node is not part of the document tree and the inherited parentNode property is always null. But it has a special behavior that makes it useful: when a request is made to insert a DocumentFragment node into the document tree, instead of inserting the DocumentFragment itself, it inserts all of its descendants. This makes the DocumentFragment a useful placeholder for temporarily storing nodes that are inserted into the document at once. It is also useful for cutting, copying, and pasting documents, especially when used with the Range interface. Can use the Document. CreateDocumentFragment () method creates a new empty DocumentFragment node


After being modified, The documentFragment will not render the browser page and will not cause redrawing and backflow of the browser. We can use it as a relay station to gather multiple DOM operations into this one. Add all dom elements that need to be added to the documentFragment first to reduce backflow times and achieve performance optimization.


Basic usage:

Initial display / / test1 < div id = "test" > < li > test1 < / li > < li > test1 < / li > < li > test1 < / li > < / div >Copy the code
Const ul = document. GetElementById (' test ') / / const objects created fragments fragments = document. CreateDocumentFragment () console.log(fragment.nodeValue); //null console.log(fragment.nodeName); //#document-fragment console.log(fragment.nodeType); // // Fetch all child nodes in ul and save to fragment let child; While (child=ul.firstChild) {fragment.appendChild(child)} // Update all nodes in the fragment. Array. The prototype. Slice. Call (fragments..childnodes). ForEach (node = > {the if (node. The nodeType = = = 1) {/ / element node node. The textContent = 'test2' // reassign to test2}}) // Insert fragment into ul ul. AppendChild (fragment)Copy the code

Therefore, using documentFragment for batch and new operations can greatly save performance.