Home  >  Article  >  Web Front-end  >  JavaScript performance optimization Create document fragments (document.createDocumentFragment)_javascript tips

JavaScript performance optimization Create document fragments (document.createDocumentFragment)_javascript tips

WBOY
WBOYOriginal
2016-05-16 18:23:16808browse

In the browser, once we add a node to document.body (or other nodes), the page will update and reflect this change. For a small amount of updates, loop insertion one by one will also work well, which is what we commonly use. method. The code is 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 (such as 1w), if we add nodes one by one like the above code, this process It may be very slow.
In order to solve this problem, we can introduce the createDocumentFragment() method, which is to create a document fragment, attach the new node to be inserted to it, and then add it to the document all at once. The code is as follows:
Copy code The code is as follows:

var oFragmeng = document.createDocumentFragment(); //Create document fragments first
for(var i=0;i<10000;i ){
var op = document.createElement("span");
var oText = document.createTextNode(i) ;
op.appendChild(oText);
oFragmeng.appendChild(op); //Append to the document fragment first
}
document.body.appendChild(oFragmeng); //Last one-time Add to document


After testing, the performance has been significantly improved under IE and Firefox. You can test it yourself.
Front-end performance optimization starts from some details. If you don’t pay attention to it, the consequences will be serious.

PS: This optimization is somewhat similar to adding html code in a loop.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn