Skip to content

Fix issue #22 #24

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 16, 2011
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 25 additions & 12 deletions content/performance/append-outside-loop.md
Original file line number Diff line number Diff line change
@@ -1,34 +1,47 @@
---
chapter : performance
section: 0
title: Cache Length During Loops
title: Append Outside of Loops
attribution: jQuery Fundamentals
tags: performance
---

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.
Touching the DOM comes at a cost; if you're appending a lot of elements to the
DOM, you will want to append them all at once, rather then one at a time. This is common problem when appending elements within a loop.

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

// better: do this
One common technique is to leverage a document fragment. During each iteration of the loop, you append the element to the fragment rather than the DOM element. After the loop, just append the fragment to the DOM element.

<div class="example" markdown="1">
var frag = document.createDocumentFragment();

$.each(myArray, function(i, item) {
var newListItem = '<li>' + item + '</li>';
frag.appendChild(newListItem);
$.each(myArray, function (i, item) {
var newListItem = document.createElement("li");
var itemText = document.createTextNode(item);
newListItem.appendChild(itemText);
frag.appendChild(newListItem);
});

$('#ballers')[0].appendChild(frag);
</div>

// or do this
Another technique, which is quite simple, is to build up a string during each iteration of the loop. After the loop, just set the html of the DOM element to that string.

<div class="example" markdown="1">
var myHtml = '';

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

$('#ballers').html(myHtml);
</div>

There are of course other techniques you could certainly test out; a great way to test the performance of these is through a site called [jsperf](http://jsperf.com). This site allows you to benchmark each technique and visually see how it performs across all the browsers.