Skip to content

Instantly share code, notes, and snippets.

@fearphage
Created September 20, 2012 14:45
Show Gist options
  • Save fearphage/3756350 to your computer and use it in GitHub Desktop.
Save fearphage/3756350 to your computer and use it in GitHub Desktop.
Can you make this faster?

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);
@dperini
Copy link

dperini commented Sep 20, 2012

Here is my jsPerf test:

http://jsperf.com/dom-fragments-and-clonenode-vs-fragments-and-innerhtml

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment