O'Reilly logo

jQuery Cookbook by Cody Lindley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

5.11. Loading Tables Faster

Problem

You’re loading a JSON data object with 1,000 names and addresses and using jQuery to create a table with this data. It takes 5–10 seconds to create the table in IE 7—and that’s not even counting the download time.

Your JSON data is in this format:

{
    "names": [
        {
            "first": "Azzie",
            "last": "Zalenski",
            "street": "9554 Niemann Crest",
            "city": "Quinteros Divide",
            "state": "VA",
            "zip": "48786"
        },
        // and repeat for 1000 names
    ]
}

Your JavaScript code is as follows:

// Return a sanitized version of text with & < > escaped for HTML
function esc( text ) {
    return text
        .replace( '&', '&amp;' )
        .replace( '<', '&lt;' )
        .replace( '>', '&gt;' );
}
$(document).ready( function() {

    function fillTable( names ) {
        $.each( names, function() {
            $('<tr>')
                .append( $('<td>').addClass('name').html(
                    esc(this.first) + ' ' + esc(this.last)
                ) )
                .append( $('<td>').addClass('address').html(
                    esc(this.street) + '<br />' +
                    esc(this.city) + ', ' +
                    esc(this.state) + ' ' + esc(this.zip)
                ) )
                .appendTo('#nameTable');
        });
    }

    $.getJSON( 'names/names-1000.json', function( json ) {
        fillTable( json.names );
    });
});

And you have this HTML code in your document:

<table id="nameTable">
</table>

It works fine, resulting in the browser display shown in Figure 5-1.

Browser output for name table

Figure 5-1. Browser output for name table

It’s just much too slow.

Solution

Combine several optimizations:

  • Insert a single <table> or <tbody> instead ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required