To test DOM manipulation versus innerHTML I deviced this little test method using a documentFragment
(web page) to append 10000 href
elements to a div
element. The performance is ok for Chrome or Firefox, but in IE (10, 9, 8) it's dramatically bad, it takes around 10-12 seconds. Can anyone explain this difference and/or elaborate on a solution to enhance performance for IE?
Here's a jsfiddle demonstrating it.
The method:
function useFragment(){
var frag = document.createDocumentFragment(),
i = 10000,
rval = document.createElement('span');
frag.appendChild(rval);
do {
var optText = 'option '+i
,ref = document.createElement('a')
,zebra = i%2 ? 'zebra' : ''
,islist = true
,isSel = i === 5
;
rval.insertBefore(ref,rval.firstChild);
ref.appendChild(document.createTextNode(optText));
ref.id = 'opt' + i;
ref.className = zebra + (islist && isSel ? ' scrollSelect' : '');
ref.href = '#' + i;
ref.title = optText;
} while (i-->0);
return rval;
}
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.