簡體   English   中英

如何在渲染時提高性能 <table> 在IE 8?

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

我有一個jquery函數,它將標記添加到表的第一行。 我嘗試使用append,但它不起作用,所以我得到了一個非常慢的解決方案,它以某種方式給出錯誤“此頁面上的腳本導致Internet Explorer運行緩慢...”

功能如

 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;
    };

任何人都可以幫助我讓這段代碼運行得更快嗎?

編輯:我必須使用IE ..這是要求(ie8)。 Edit2:我創建了js小提琴: http//jsfiddle.net/4xLzL/

要提高渲染性能,您必須了解DOM操作(包括回流和重新繪制)是昂貴的操作。 您的代碼當前重新創建了整個表,其中<thead>添加了大部分<tbody>內容保持不變。 這種大規模的“重繪”表非常低效。 特別是在IE 8中,渲染表格太慢,你必須盡可能少地修改DOM。

我重構了你的邏輯,通過將元素保存到一個可以重用的變量來最小化查找元素所執行的查找次數。 此外,刪除了重新呈現表的.html('...')調用,而是使用.prepend()函數將<thead> <table>作為第一個子項添加到<table>中。

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();
});

繼續在IE8中測試它: http//jsfiddle.net/amyamy86/4xLzL/7/

問題不在於插件,而在於您的選擇器。 您只需要表,因此請將選擇器修改為如下所示。

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

我也更新了小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM