Pingpong
Pingpong

Reputation: 8009

Javascript efficiency improvement on appendChild Method

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.

Upvotes: 3

Views: 1775

Answers (3)

elliot
elliot

Reputation: 51

You can use DocumentFragment, a lightweight node container which prevents DOM from refreshing and reflowing when you append nodes on it.

var nodeHolder = document.createElement('div'),
    fragment = document.createDocumentFragment();
for (var i = 0; i < 1000; i ++ ) {
    var el = document.createElement('div');
    el.innerHTML = 'Node ' + (i + 1);
    fragment.appendChild(el);
}
nodeHolder.appendChild(fragment);

Upvotes: 1

user113716
user113716

Reputation: 322492

Create a document fragment and append to that, then do a single append for the entire set.

var frag = document.createDocumentFragment();

for(var i = 0; i < 1000; i += 1){
    var el = document.createElement('div');
    el.appendChild(document.createTextNode('Node ' + (i + 1)));
    frag.appendChild(el);
}

document.getElementById('nodeHolder').appendChild( frag );

Now your getElementById only 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/

var frag = document.createDocumentFragment();

for(var i = 0; i < 1000; i += 1){
    frag.appendChild(document.createElement('div'))
        .appendChild(document.createTextNode('Node ' + (i + 1)));
}

document.getElementById('nodeHolder').appendChild( frag );

Additionally, a very minor optimization would be to get rid of the i + 1, and modify the for loop to provide the values you want.

Example: http://jsfiddle.net/7hagb/1/

var frag = document.createDocumentFragment();

for(var i = 1; i <= 1000; i += 1){
    frag.appendChild(document.createElement('div'))
        .appendChild(document.createTextNode('Node ' + i));
}

document.getElementById('nodeHolder').appendChild( frag );

Upvotes: 7

mkk
mkk

Reputation: 7693

do not use DOM, just use html instead. for example instead of createElement use

  abc = ""
  for(...){
  abc += "<div>Text " + i + "</div>";
  }

and then append to the target. It is ugly, I agree, but should run much faster

Upvotes: 0

Related Questions