Skip to content

Commit b4556af

Browse files
committed
Fix issue jquery#23, as well fixing the title and beefing up the description to the solutions
1 parent 0ec7894 commit b4556af

File tree

1 file changed

+25
-12
lines changed

1 file changed

+25
-12
lines changed
+25-12
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,47 @@
11
---
22
chapter : performance
33
section: 0
4-
title: Cache Length During Loops
4+
title: Append Outside of Loops
55
attribution: jQuery Fundamentals
66
tags: performance
77
---
88

9-
Touching the DOM comes at a cost; if you're adding a lot of elements to the
10-
DOM, do it all at once, not one at a time.
9+
Touching the DOM comes at a cost; if you're appending a lot of elements to the
10+
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.
1111

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

18-
// better: do this
19+
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.
20+
21+
<div class="example" markdown="1">
1922
var frag = document.createDocumentFragment();
2023

21-
$.each(myArray, function(i, item) {
22-
var newListItem = '<li>' + item + '</li>';
23-
frag.appendChild(newListItem);
24+
$.each(myArray, function (i, item) {
25+
var newListItem = document.createElement("li");
26+
var itemText = document.createTextNode(item);
27+
newListItem.appendChild(itemText);
28+
frag.appendChild(newListItem);
2429
});
30+
2531
$('#ballers')[0].appendChild(frag);
32+
</div>
2633

27-
// or do this
34+
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.
35+
36+
<div class="example" markdown="1">
2837
var myHtml = '';
2938

3039
$.each(myArray, function(i, item) {
31-
html += '<li>' + item + '</li>';
40+
myHtml += '<li>' + item + '</li>';
3241
});
42+
3343
$('#ballers').html(myHtml);
44+
</div>
45+
46+
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.
3447

0 commit comments

Comments
 (0)