For the purpose of this question lets say we need to append()
1000 objects to the body
element.
You could go about it like this:
for(x = 0; x < 1000; x++) {
var element = $('<div>'+x+'</div>');
$('body').append(element);
}
This works, however it seems inefficient to me as AFAIK this will cause 1000 document reflows. A better solution would be:
var elements = [];
for(x = 0; x < 1000; x++) {
var element = $('<div>'+x+'</div>');
elements.push(element);
}
$('body').append(elements);
However this is not an ideal world and this throws an error Could not convert JavaScript argument arg 0 [nsIDOMDocumentFragment.appendChild]
. I understand that append()
can't handle arrays.
How would I using jQuery
(I know about the DocumentFragment node, but assume I need to use other jQuery functions on the element such as .css()
) add a bunch of objects to the DOM at once to improve performance?
Since $.fn.append takes a variable number of elements we can use
apply
to pass the array as arguments to it:This works if you have an array of jQuery objects. According to the spec though you can append an array of elements if you have the DOM elements. If you have an array of html strings you can just .join('') them and append them all at once.
Upgrade to jQuery 1.8, this works as intended: