I’m sorry if this is a novice question, but I’m not very knowledgeable when it comes to Javascript…
So, here’s the code snippet:
function insertSquares() {
for (i = 0; i < 113; i++) {
$('#wrapper').append('<span><img src="images/square_2.png" style='display: none;'/></span>');
}
}
As you can see, I have a loop that appends a <span> and an <img> to a <div> each time that the code is repeated. Normally, this appending isn’t a problem, but since it has to do this a number of times in the loop, so it takes a while. (also, this function is called a number of times by a setInterval(), and it slows down the entire webpage)
When benchmarking this function with JSLitmus, it runs 5 ops/sec, and I would like to speed this up. I have already thought of using the loop to add the data to an array instead, (rather than appending each time through the loop) and then when outside of the loop, appending all of the data only once, but this does not seem to speed up the process by a noticeable amount.
So, is there some way I can speed this code up that I haven’t thought of? I can’t think of a more efficient way to load and display this amount of the same image.
The best thing you can do is wait until you’ve finished the loop to make your changes to the DOM. Your current method will hammer the DOM into submission, and you certainly don’t want this. Consider Document Fragments instead.
John Resig wrote about DOM Document Fragments some time back, but the post is still a good primer. You can find it online at http://ejohn.org/blog/dom-documentfragments/.