Bad performance IE using documentFragment

后端 未结 2 1934
野性不改
野性不改 2021-01-21 06:48

To test DOM manipulation versus innerHTML I deviced this little test method using a documentFragment (web page) to append 10000 href elements to a

2条回答
  •  时光说笑
    2021-01-21 07:24

    As far as my experience goes the best benefits are to append a lot isolated elements to the fragment and to append that element not before all children and attributes are fixed (post append). If I understand your code (I'm to lazy to decode it really) there is one span you append to the fragment. This is not the sense of documentFragment. By the way: You shouldn't declare your vars in a loop.

    var node=document.getElementById("whatever")
       ,frag=document.createDocumentFragment()
       ,i=0,len=50,a={},img={};
    for(i;i

    This way IE8 Opera12 takes quite the same time than innerHTML. The real benefit has chrome. FF is unbelievable fast with innerHTML. Tested on an old XP machine.

    Another thing to think of is to create a node not connected to the DOM with all children and attributes, to clone it several times, to manipulate it and to append it to a documentFragment.

    var frag=document.createDocumentFragment()
       ,toFill=document.getElementById("imageCollection")
       ,i=0,a={},img={}
       ,dummy=document.createElement("a")
       ;
    dummy.innerHTML="";   
    for(i;i<50;i++){
       a=dummy.cloneNode(true);
       img=a.getElementsByTagName("img")[0];
       a.href="description_"+i+".html";
       img.src+=i+".png";
       frag.appendChild(a);
       }            
    toFill.appendChild(frag);   
    

    This is useful if you don't need to make a lot of manipulations on the cloned node.

提交回复
热议问题