I want to alter the following Java script to make it more efficient
for(var i = 0; i < 1000; i += 1){
var el = document.createElement('div');
el.appendChild(document.createTextNode('Node ' + (i + 1)));
document.getElementById('nodeHolder').appendChild(el);
}
Ideally it would be grateful if the reason behind it could be provided.
Any idea would be very much appreciated.
Create a document fragment and append to that, then do a single append for the entire set.
Now your
getElementByIdonly needs to run once, and the DOM only needs to update once.The document fragment is a generic container. When appending it to the DOM, the container just disappears, and only its content is appended.
You can condense the code a bit if you like:
Example: http://jsfiddle.net/7hagb/
Additionally, a very minor optimization would be to get rid of the
i + 1, and modify theforloop to provide the values you want.Example: http://jsfiddle.net/7hagb/1/