Search

7/23/2008

Ajaxian » Increase DOM Node Insertion Performance

Ajaxian » Increase DOM Node Insertion Performance
High Performance Ajax Applications


var div = document.getElementsByTagName("div");
var fragment = document.createDocumentFragment();
for ( var e = 0; e <elems.length; e++ )
fragment.appendChild( elems[e] );
}

for ( var i = 0; i <div.length; i++ ) {
div[i].appendChild( fragment.cloneNode(true) );
}

Efficient JavaScript - Opera Developer Community
Cross device development techniques for widgets - Opera Developer Community
Document tree modification will trigger reflow. Adding new elements to the DOM, changing the value of text nodes, or changing various attributes will all be enough to cause a reflow. Making several changes one after the other, may trigger more than one reflow, so in general, it is best to make multiple changes in a non-displayed DOM tree fragment. The changes can then be made to the live document's DOM in one single operation:
var docFragm = document.createDocumentFragment();
var elem, contents;
for( var i = 0; i < textlist.length; i++ ) {
elem = document.createElement('p');
contents = document.createTextNode(textlist[i]);
elem.appendChild(contents);
docFragm.appendChild(elem);
}
document.body.appendChild(docFragm);

Document tree modification can also be done on a clone of the element, which is then swapped with the real element after the changes are complete, resulting in a single reflow. Note that this approach should not be used if the element contains any form controls, as any changes the user makes to their values, are not reflected in the main DOM tree. It should also not be done if you need to rely on event handlers being attached to the element or its children, since in theory they should not be cloned.
var original = document.getElementById('container');
var cloned = original.cloneNode(true);
cloned.setAttribute('width','50%');
var elem, contents;
for( var i = 0; i < textlist.length; i++ ) {
elem = document.createElement('p');
contents = document.createTextNode(textlist[i]);
elem.appendChild(contents);
cloned.appendChild(elem);
}
original.parentNode.replaceChild(cloned,original);

沒有留言: