Javascript performance optimization creates document fragments (document. createdocumentfragment)

Source: Internet
Author: User

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.

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.