Is there a difference between using a document fragment or an un-appended created div to avoid multiple hits to the DOM?
Let's say we're going to generate 100 list items...
Our page's contents:
<ul class="list"></ul>
Scenario 1: document fragment
In this scenario, we're creating the li, populating it with some simple text, then appending it to the fragment. Once the loop is finished, the fragment gets appended to the list. We avoid pinging the DOM 100x's and only ping it once to append the fragment.
var frag = document.createDocumentFragment();
for(var i = 1; i <= 100; i++) {
var li = document.createElement('li');
li.textContent = 'Item #' + i;
frag.append(li);
}
document.querySelector('.list').appendChild(frag);
Scenario 2: un-appended div
In this scenario, we create a div that acts like the document fragment since it's not in the DOM. We append all the created li's to the div, then finally append the div's contents to the list in the DOM.
var div = document.createElement('div');
for(var i = 1; i <= 100; i++) {
var li = document.createElement('li');
li.textContent = 'Item #' + i;
div.append(li);
}
document.querySelector('.list').innerHTML = div.innerHTML;
What's the difference between these two scenario's? As far as avoiding pinging the DOM multiple times, it seems that both achieve the same result.