Append Outside of Loops
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.
1
2
3
4
5
6
7
|
|
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
|
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.
1
2
3
4
5
6
7
8
9
|
|
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. This site allows you to benchmark each technique and visually see how it performs across all the browsers.