user1181942
user1181942

Reputation: 1607

How to improve performance when rendering <table> in IE 8?

I have a jquery function which adds tag to first row of table. I tried using append, however its not working, so i got a solution which is very slow and it somehow gives error "Script on this page is causing internet explorer run slow..."

Function is as

 jQuery.fn.fixGridView = function () {
        "use strict";
       // var start = +new Date();  // log start timestamp 
        if (jQuery(this).is('table') && this.find('thead').length === 0) {

            var theadv = "<thead><tr>" + this.find('tbody tr:first').html(); +"</tr></thead>";

            this.find('tbody tr:first').remove();
            var htmlv = this.html();
            this.html(theadv + htmlv);
        }
        //var end = +new Date();  // log end timestamp
       // var diff = end - start;
       // alert(diff);
        return this;
    };

Can anybody help me to make this code run faster?

EDIT: I have to use IE..that is the requirement (ie8). Edit2: I have created js fiddle: http://jsfiddle.net/4xLzL/

Upvotes: 0

Views: 191

Answers (2)

Amy
Amy

Reputation: 7466

To increase rendering performance you must understand that DOM manipulation (including reflows & repaints) are expensive operations. Your code currently re-creates the entire table with the <thead> added the majority of the <tbody> content remains the same. This massive "redraw" of the table is highly inefficient. Especially when in IE 8, where rendering tables is extra slow, you have to modify the DOM as little as possible.

I've refactored your logic to minimize the number of lookups performed to find elements by saving them to a variable to be re-used. Also, removed the .html('...') call that re-renders the table, but instead used the .prepend() function to add the <thead> into the <table> as the first child.

jQuery.fn.fixGridView = function () {
    "use strict";
    var start = +new Date(); // log start timestamp 
    if (this.is('table') && this.children('thead').length === 0) {

        var firstRow = this.children('tbody').children('tr:first');
        var thead = "<thead><tr>" + firstRow.html() + "</tr></thead>";
        firstRow.remove();
        this.prepend(thead);
    }
    var end = +new Date(); // log end timestamp
    var diff = end - start;
    alert(diff);
    return this;
};

$(document).ready(function () {
    $('table[id*="gvCategories"]').fixGridView();
});

Go ahead and test it in IE8: http://jsfiddle.net/amyamy86/4xLzL/7/

Upvotes: 2

Kent Anderson
Kent Anderson

Reputation: 486

The problem is not with the plugin, but with your selector. You only want tables, so modify your selector to be as follows.

$('table [id*="gvCategories"]').fixGridView();

I also updated the fiddle.

Upvotes: 0

Related Questions