I have 464 JSON objects. An HTML element needs to be generated from each of these elements, and inserted into a div in sequential order. What’s going to be the fastest way to render this?
A) Loop through the objects, generating markup for each, concatenating them all, and setting the innerHTML of the container div to the concatenated markup:
document.getElementById("container").innerHTML =
jsonItems.map(function(item) {
return convertToHTMLString(item);
}).join("");
B) Loop through the objects, generating a DOM node for each, and inserting each sequentially into container:
var container = document.getElementById("container");
jsonItems.forEach(function(item) {
container.appendChild(convertToDOMNode(item));
});
C) Loop through the objects, generating a DOM node for each, sequentially appending them to a DocumentFragment, then inserting the fragment into the container:
var fragment = document.createDocumentFragment();
jsonItems.forEach(function(item) {
fragment.appendChild(convertToDOMNode(item));
});
document.getElementById("container").appendChild(fragment);
Benchmark
The correct answer is please benchmark it yourself 🙂
I personally think
.innerHTMLis the devil so use document fragments.And I think we all know document fragments are superior to injecting data directly into the DOM. It’s the exact same logic as rendering stuff off the screen then swapping it back in.