开发者

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 p开发者_StackOverflow中文版rovided.

Any idea would be very much appreciated.


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 );


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);


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜