To test DOM manipulation versus innerHTML I deviced this little test method using a documentFragment
(web page) to append 10000 href
elements to a
Think I've found it: it looks like, although a documentFragment
should be an 'off line' element (an element that is not part of the live DOM) IE doesn't treat it as such. The way to force the fragment to really be off line is to append some element to it, set its display
property to none
and append the rest of elements to that element. After you are done, remove the display:none
property and the documentFragment
can be appended to the DOM.
It is still three times slower (on my PC it still takes around 1-1.5 seconds, versus around 2-300 ms in Chrome/Firefox for 10000 elements). So, for IE (even version 10), using innerHTML
to add a bunch of elements to the DOM is the faster way. IE remains a developers nightmare, I'd say.
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<len;i++){
a=document.createElement("a");
img=document.createElement("img");
a.href="image"+i;
img.className=J[i][1];
img.src="image/img"+i+".png";
img.alt="image:"+i;
a.appendChild(img);
frag.appendChild(a);
}
node.appendChild(frag);
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="<img src='img/image_' />";
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.