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?
You could just call
Or you can just create a large string in the first place.
Like you mentioned, probably the most "correct" way is the usage of a DocFrag. This could look like
.textContent
is not supported by IE<9 and would need an conditional check to use.innerText
or.text
instead.If you're going for raw performance then I would suggest pure JS, though some would argue that your development performance is more important than your site's/program performance. Check this link for benchmarks and a showcase of different DOM insertion techniques.
edit:
As a curiosity,
documentFragment
proves to be one of the slowest methods.Sometimes, jQuery isn't the best solution. If you have a lot of elements to append to the DOM,
documentFragment
is a viable solution:I would use native Javascript, normally much faster:
EDIT:
There you go a jsfiddle with different options implemented. The @jackwander's solution is, clearly, the most effective one.
A slight change to your second approach:
$.append() certainly can append an array: http://api.jquery.com/append/
You could use an empty jQuery object instead of an array:
This might be useful if you want to do stuff with newly generated element inside the loop. But note that this will create a huge internal stack of elements (inside the jQuery object).
It seems though that your code works perfectly fine with jQuery 1.8.