JavaScript performance Optimization Create document fragmentation (document.createdocumentfragment) _javascript tips

Source: Internet
Author: User
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.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.