简体   繁体   中英

Rebuild element in jQuery vs. mass showing/hiding

I have a paginated table of data that I want to cache client-side and I'm trying to figure out how to most efficiently switch pages.

Would it be better to do:

A. Rebuild and replace the table via one modification to the DOM

var pageLength = 50;
var cache; //array of some objects from database

function changePage(index) {
    var $table = $("<table>");
    $.each(cache, function (i, row) {
        var $tr = $("<tr>");
        if (i < index || i > index + pageLength) $tr.hide();
        $tr.append($("<td>", { text: row.ID }));
        $tr.append($("<td>", { text: row.Name }));
        $table.append($tr);
    });
    $("#targetDiv").html($table);
}

or

B. Showing and hiding the rows after inserting into the DOM

function changePage(index) {
    var $table = $("#targetDiv table");
    $table.find("tr:visible").hide();
    $table.find("tr").each(function (i, row) {
        if (i > index && i < index + pageLength) $tr.show();
    });
}

I wrote something along the lines of the first one and ran it in Chrome vs IE8 and found IE was very noticeably slower, whereas Chrome had no problem. Our standard is still IE7 unfortunately, so I'm trying to optimize in the likely event the JS engine in IE7 is worse performance-wise than IE8.

I would do a combination of both.

On load you would show page one (with a reference to your complete list stored somewhere).

When page two is requested you would populate it with page two data and hide page one.

When page two is requested another time it would already be populated so it would be a hide/show function.

This would best be handled by a class that knows which page is current, how many pages there could be, etc. Then when you could do some smart memory management where you can empty pages that are a certain number of pages away from the current page.

But I would recommend using an existing solution

There are MANY client side paging plugins, especially for jQuery.

  • DataTables is something I have used in the past and while it's a bit of a struggle to begin with it's highly extensible.
  • Here is a List of jQuery plugins that google directed me to.

I would go with an existing solution and not try to re-invent the wheel here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM