Faster YUI DataTable with 5 Lines of Code

Holy Reflows Batman! The typical usage of a DataTable in the Yahoo User Interface JavaScript library involves passing a string into the constructor signifying the ID attribute of the container you want to attach the DataTable to. However, the YUI DataTable loves the DOM and creating nodes individually using DOM methods. Normally that’d be fine, but one of the first things it does in the constructor is create the table element and attach it to the live DOM. This is a no-no. Now, every time they append a new node (for a new row or a new cell inside of a row), it causes a reflow in the browser! What does this mean? Really bad lag when you insert 40 or 50 rows. Recognize this piece of code?

var myDataTable = new YAHOO.widget.DataTable("myContainer", myColumnDefs, myDataSource);

Straight from the docs. No no no!

Instead, you should pass in an unattached DOM node instead of a string!

Try this code on for size:

var myDataTable = new YAHOO.widget.DataTable(document.createElement('div'), myColumnDefs, myDataSource); 
myDataTable.subscribe('initEvent',function() {
    var d = document.getElementById('myContainer'); // CHANGE THIS -- match the id of the container you want.
    while(d.firstChild) { d.removeChild(d.firstChild); }; // remove previous DataTables
    d.appendChild(this._elContainer); });
}
VN:F [1.8.4_1055]
Rating: 0.0/5 (0 votes cast)
This entry was posted in JavaScript and tagged , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.
  • Thanks for reading. If you found this article useful, and you've read through some of my previous articles, you might as well Subscribe to my content subscribe to my blog. You'll save me some bandwidth that way.

One Comment

  1. Zach Leatherman
    Posted January 3, 2008 at 10:19 am | Permalink

    Outstanding bug that will be addressed in the next version:

    “initEvent cannot be listened to for local sources”

    http://sourceforge.net/tracker/index.php?func=detail&aid=1844094&group_id=165715&atid=836476

    Keep that in mind when using this approach.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Additional comments powered by BackType