Monday, September 15, 2008

createDocumentFragment() in Javascript

For some javascript developers like me, I never used and even heard this method createDocumentFragment(). I have learned and read many javascript books (about 10), but most of them didn't mention this method at all. Today, I just encounter this method when I read my existing book on one chapter how to sort table in javascript. I saw the author use this method. This book named "Wrox - Javascript for Web Developers".

"createDocumentFragment()" is basically somewhere to store your newly created nodes before you append them to the document. When you are ready to append all the nodes to the document, all you need to do is one append and they all get added. Creating a fragment is extremely easy.


var docFragment = document.createDocumentFragment();


You now have somewhere to store your new nodes. To add nodes to the fragment, all you need to do is append the childs to the fragment.


function myFunction() {
   var docFragment = document.createDocumentFragment();
   docFragment.appendChild(document.createTextNode("my text node 1"));
   docFragment.appendChild(document.createTextNode("my text node 2"));
   return docFragment;
}


After this, call

document.body.appendChild(myFunction());

No comments:

Subscribe in a Reader