In the browser, once we add the nodes to the document.body (or other nodes), the page will update and reflect this change, for a small number of updates, a circular insert will also run well, is also our common method. The code is as follows:
Copy Code code 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 (such as 1w), this process can be very slow if you add nodes one at a time like the code above.
To solve this problem, we can introduce the Createdocumentfragment () method, which is to create a document fragment, attach the new node to be inserted on it first, and then add it to the document at once. The code is as follows:
Copy Code code 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 to document fragmentation first
}
Document.body.appendChild (Ofragmeng)//last added to document
After testing, the performance of the Ie,firefox is obviously improved. We can test it by ourselves.
The front-end performance optimization is done from a number of details, if not attention, the consequences are serious.
PS: This optimization is a bit like looping with adding HTML code.