Append new content outside of a loop
Prev Chapter 9. Performance Best Practices Next

Append new content outside of a loop

Touching the DOM comes at a cost; if you're adding a lot of elements to the DOM, do it all at once, not one at a time.

// this is bad
$.each(myArray, function(i, item) {
   var newListItem = '<li>' + item + '</li>';
   $('#ballers').append(newListItem);
});

// better: do this
var frag = document.createDocumentFragment();

$.each(myArray, function(i, item) {
    var newListItem = '<li>' + item + '</li>';
    frag.appendChild(newListItem);
});
$('#ballers')[0].appendChild(frag);

// or do this
var myHtml = '';

$.each(myArray, function(i, item) {
    html += '<li>' + item + '</li>';
});
$('#ballers').html(myHtml);

Copyright Rebecca Murphey, released under the Creative Commons Attribution-Share Alike 3.0 United States license.


Prev Up Next
Chapter 9. Performance Best Practices Home Keep things DRY