Document. createDocumentFragment () is to save on DOM usage. Every JavaScript operation on DOM changes the realization of the page and refresh the whole page, which consumes a lot of time. To solve this problem, you can create a File Fragment, attach all the new nodes to it, and add the content of the file fragment to the document at one time.
This is a simple test page I wrote:
Copy codeThe Code is as follows:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312"/>
<Title> document. createDocumentFragment () test page </title>
</Head>
<Body>
<Script type = "text/javascript">
Var d1 = new Date ();
For (var I = 0; I <1000; I ++)
{
Var op = document. createElement ("P ");
Var oText = document. createTextNode ("test1 ");
Op. appendChild (oText );
Document. body. appendChild (op );
}
Var d2 = new Date ();
Document. write ("Method 1:" + (d2.getTime ()-d1.getTime () + "<br/> ");
// --- + -----
Var d3 = new Date ();
Var oFrag = document. createDocumentFragment ();
For (var I = 0; I <1000; I ++)
{
Var op = document. createElement ("P ");
Var oText = document. createTextNode ("test2 ");
Op. appendChild (oText );
OFrag. appendChild (op );
}
Document. body. appendChild (oFrag );
// In this Code
Var d4 = new Date ();
Document. write ("Method 2:" + (d4.getTime ()-d3.getTime () + "<br/> ");
</Script>
</Body>
</Html>
Once a node is added to document. body (or the subsequent node), the page immediately reflects this change. For the first short program, there is no problem in running, but the problem is that it calls the document ten times. body. appendChild () generates a page refresh every time, which will generate many page fragments. In the second code segment, document. body. appendChild () is called only once, which means that only one page refresh is required, and the time needed is obviously less than the previous one.
I used three browsers to test the above test code. The general result is:
IE7:
Method 1: 140
Method 2: 125
Firefox:
Method 1: 66
Method 2: 43
Chrome:
Method 1: 35
Method 2: 25
The result is still consistent with the theoretical one.