The goal is to add N new elements to the DOM as quickly and as painlessly as possible.
I have access to jQuery and found the code below to be faster than the following:
$(parentElement)
.append(Array(1001).join(template))
;
var | |
fragment = document.createDocumentFragment() | |
,div = document.createElement('div') | |
,temp = '<div class="foo"><a href=#">bar</a><span class="catpants">baz</span></div>' | |
; | |
div.innerHTML = Array(1001).join(temp); | |
while (temp = div.firstChild) { | |
fragment.appendChild(temp); | |
} | |
parentElement.appendChild(fragment); |
A typo in the previous snippet, should be:
while (1000 > i++) fragment.appendChild(tmp.cloneNode(true));
You might wanna take the performance testing to jsPerf, guys ;)
Very nice gentlemen. I have a few ideas to test now. Thanks a lot.
Here is my jsPerf test:
http://jsperf.com/dom-fragments-and-clonenode-vs-fragments-and-innerhtml
Yes fragments + cloneNode() is always faster than innerHTML, at least that's what I tested long ago.
Take this as a start:
tested on Chrome/Opera to be almost 2x faster, and on Firefox/Safari still faster but not that much.