When we develop with native JS, we often use two methods of updating DOM nodes: InnerHTML and AppendChild (). Where InnerHTML will completely replace the original node content, if we want to append to the element, then InnerHTML obviously can not meet the demand. In turn we will think of the AppendChild () method. The AppendChild method receives a single node-type object for the parameter type. So when we want to add multiple child nodes, we can only do it through loops.
For example:
for (var i = things.length-1; I >= 0; i--) { element.appendchild (things[i]);}
As we all know, the greater the number of operations on the DOM, the greater the performance cost. Loops like this add a node, how many times it is cycled, how many times the DOM is manipulated, and the performance cost is obviously not cost-effective. We would like to be able to package the node to be inserted, and then add it at once? If you can, then only one operation is done on the DOM. To achieve packaging, it is necessary to use our protagonist Createdocumentfragment.
Documentfragments is a DOM node. They are not part of the main DOM tree. The usual use case is to create a document fragment, attach the element to the document fragment, and then attach the document fragment to the DOM tree. In the DOM tree, the document fragment is replaced by all its child elements. Because a document fragment exists in memory and not in the DOM tree, inserting child elements into a document fragment does not cause the page to reflow (calculations on the position and geometry of the element). Therefore, using document fragments often leads to better performance.
Example: Creating a list of major web browsers
Html
<id= "ul"></ul>
Javascript
var element = document.getElementById (' ul '); var fragment = document.createdocumentfragment (); var browsers = [' Firefox ', ' Chrome ', ' Opera ', ' Safari ', ' Internet Explorer ']; Browsers.foreach (function(browser) { var li = document.createelement (' li ' ); = browser; Fragment.appendchild (LI); //Here to insert a child node into a document fragment without causing reflux (equivalent to packing operation)}); Element.appendchild (fragment); //Insert a packaged document fragment into the UL node and do only one operation
Reference: Https://developer.mozilla.org/zh-CN/docs/Web/API/Document/createDocumentFragment
JS Performance Optimization Document fragment Createdocumentfragment