/
append.html
52 lines (45 loc) · 1.47 KB
/
append.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<!doctype html>
<html lang="en">
<head>
<title>JavaScript Patterns</title>
<meta charset="utf-8">
</head>
<body>
<script>
/* Title: append
* Description: use string concatenate and set innerHTML. Note that it is recommended to use the
* array.join technique to concatenate long strings.
*/
// antipattern
// appending inside
$.each(reallyLongArray, function (count, item) {
var newLI = '<li>' + item + '</li>';
$('#ballers').append(newLI);
});
// documentFragment off-DOM
var frag = document.createDocumentFragment();
$.each(reallyLongArray, function (count, item) {
var newLI = $('<li>' + item + '</li>');
frag.appendChild(newLI[0]);
});
$('#ballers')[0].appendChild(frag);
// string concatenate and set innerHTML
var myhtml = '';
$.each(reallyLongArray, function (count, item) {
myhtml += '<li>' + item + '</li>';
});
$('#ballers').html(myhtml);
// concatenate very long strings
var myHtmlBuffer = [];
$.each(reallyLongArray, function(count, item) {
myHtmlBuffer.push('<li>' + item + '</li>');
});
$('#ballers').html(myHtmlBuffer.join(''));
// References
// http://paulirish.com/2009/perf/
// http://www.sitepen.com/blog/2008/05/09/string-performance-an-analysis/
// http://stackoverflow.com/questions/112158/javascript-string-concatenation
// http://stackoverflow.com/questions/153381/javascript-string-concatenation-faster-than-this-example
</script>
</body>
</html>