I am populating a list with about 25,000 items, using code like this:
var html = "";
for(var i = 0; i < reallyLongArray.length; i++) {
html += "<li><a href='#'>Hi</a></li>";
}
$("#list ol").html(html);
Somewhat to my surprise, I used a profiler and found out that the bottleneck in my code was not the loop that iterated thousands of times, but setting the html of the list to the string. This usually takes about 5-10 seconds on my computer, which is an order of magnitude too slow.
Is there a way to do this that is significantly faster, i.e., at least 10 times faster?
Wrap the html in a single item. When jQuery builds elements from a string, it adds all top level items by iterating them. If you wrap the list items in a single element, it should go much faster because it only has to add 1 top level element to the dom.
var html = "<ul>";
// your loop...
var html += "</ul>";
// add list html to list container
Aside from directly using innerHTML
:
$("#list ol").get(0).innerHTML = html;
...and trying the "stringbuffer" technique:
var html = [];
for(i = 0; i < reallyLongArray.length; i++) {
html.push("<li><a href='#'>Hi</a></li>");
}
$("#list ol").html(html.join(''));
...not really.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With