In the browser, once we add the node to document. in the body (or other nodes), the page will update and reflect this change. For a small number of updates, loop insertion will also run well, which is also a common method. Code As follows:
Copy code The Code is as follows: for (VAR I = 0; I <5; I ++ ){
VaR op = Document. createelement ("span ");
VaR otext = Document. createtextnode (I );
Op. appendchild (otext );
Document. Body. appendchild (OP );
}
However, if we want to add a large amount of data to the document (for example, entries), the process may be very slow if we add nodes one by one like the code above.
To solve this problem, we can introduce the createdocumentfragment () method, which creates a File Fragment and attaches the new node to be inserted to it first, and then add it to the document. The Code is as follows:Copy codeThe Code is as follows: var ofragmeng = Document. createdocumentfragment (); // create a document fragment first
For (VAR I = 0; I <10000; I ++ ){
VaR op = Document. createelement ("span ");
VaR otext = Document. createtextnode (I );
Op. appendchild (otext );
Ofragmeng. appendchild (OP); // attach the object to the File Fragment first.
}
Document. Body. appendchild (ofragmeng); // Add the object to the document at the last time.
After testing, the performance in IE and Firefox is significantly improved. You can test it on your own.
Front-end performance optimization starts from some details. If you do not pay attention to it, the consequences are very serious.
PS: This optimization is a bit similar to adding HTML code cyclically.