In JavaScript dynamic insertion technology, I introduced the technology of converting innerhtml into document fragments, which is used by various major libraries. But in fact, if our strings do not have the th, tbody, Col, and other tags that need to be packaged for dynamic generation, there is no such annoying script tag, we still have many methods to improve performance, such as insertadjacenthtml. However, if you want to use insertadjacenthtml, there are many restrictions. For example, to avoid innerhtml as a read-only element in IE, FF must be supported in a very high version, and call objects (such as jquery) the element can only be a node, not a string. Therefore, in many cases, we need to convert it into a node set first, today I am introducing the use of createcontextualfragment to directly convert strings to document fragments!
In the traditional innerhtml method, a redundant Div element is generated as a converter, and then a File Fragment is created using createdocumentfragment, which is transferred from one node to another. If createcontextualfragment is used, this step can be avoided.
// Http://www.cnblogs.com/rubylouvre/archive/2011/04/15/2016800.html var STR = '<div> <strong> test </strong> </div>'; var range = document. createRange (); range.selectnodecontents(document.doc umentelement); var fragment = range. createcontextualfragment (STR); document. body. appendchild (fragment );
<br/> <! Doctype HTML> <br/> <pead> <br/> <title> efficiently converts strings to file fragments by situ zhengmei </title> <br /> <SCRIPT> </P> <p> window. onload = function () {<br/> try {<br/> var STR = '<div> <strong> test </strong> </div> '; <br/> var range = document. createRange (); <br/> range.selectnodecontents(document.doc umentelement); <br/> var fragment = range. createcontextualfragment (STR); <br/> document. body. appendchild (fragment); </P> <p>} catch (E) {}</P> <p >}</P> <p> </SCRIPT> <br/> </pead> <br/> <body> </P> <p> </body> <br/> </ptml> <br/>
RUN Code
<Br/> <! Doctype HTML> <br/> <pead> <br/> <title> Performance Test by situ zhengmei </title> <br/> <SCRIPT> <br/> window. onload = function () {<br/> try {<br/> var STR = '<Div class = "calendar" id = "pager-top"> <a rel = "Prev" href =" # "class =" Prev "> AAA </a> <SPAN class =" edit-in-place-Add "> </span> </div> '; <br/> var start = new date; <br/> for (VAR I = 0, firstchild; I </P> <p> <button type = "button" Title = "runcode2" class = "runcode"> run the Code </button> </P> <Table> </table> <Table border = "1" width = "60%"> <tr> <TD> Brower </TD> <TD> innerhtml </TD> <TD> createcontextualfragment </TD> </tr> <TD> chrome12 </TD> <TD> 34 </TD> <TD> 70 </TD> </tr> <tr> <TD> chrome14 </TD> <TD> 15 </TD> <TD> 40 </TD> </tr> <TD> ff4 </TD> <TD> 36 </TD> <TD> 33 </TD> </tr> <TD> ff7 </TD> <TD> 24 </TD> <TD> 18 </TD> </tr> <TD> opera10 </TD> <TD> 28 </TD> <TD> 17 </TD> </ tr> <TD> opera11.51 </TD> <TD> 8 </TD> <TD> 7 </TD> </tr> </table> <p>