如何加快javascript表的渲染速度?

时间:2014-01-28 04:15:03

标签: javascript html performance html-table

我正在使用javascript在页面加载上构建一个大表,我现在能够在大约2秒内加载表部分(当然在我的机器上)。但是,我希望它会更快。有任何改进建议吗?

var fragment = document.createDocumentFragment();
var table=document.createElement('table')
table.className="table-bordered"
fragment.appendChild(table)
var body=document.createElement('tbody')
table.appendChild(body)
for (var i = 0; i < 200; i++) {
    var row = document.createElement('tr');
    body.appendChild(row);

    for (var j = 0; j < 100; j++) {
        var cell = document.createElement('td');

       if(j!==0)
       {cell.id="row"+i.toString()+"col"+(j-1).toString()
       cell.className="myclass"
        }
        row.appendChild(cell);
    }
 }

3 个答案:

答案 0 :(得分:3)

尝试将此行:fragment.appendChild(table)移到代码的最后。

否则,您正在更新附加到DOM的表,并且每次添加新元素时它都可能尝试重新呈现内容。

答案 1 :(得分:1)

DOM呈现可能是瓶颈,因此改进代码可能无济于事。但是,我可以提出一些改变:

// declare all variables at head of code section--won't increase speed, but is good practice
var fragment = document.createDocumentFragment(),
    table = document.createElement('table'),
    body = document.createElement('tbody'),
    i = 200, 
    j = 100,
    row, cell;

table.className = "table-bordered";
table.appendChild(body);

// reverse while loop is faster than a traditional for loop
while(i--) {
    row = document.createElement('tr');
    body.appendChild(row);

    while(j--) {
        cell = document.createElement('td');

        if(j !== 0) {
            cell.id = ["row", i, "col", (j - 1)].join(""); // here we're joining an array instead of concatenating
                                                           // a string. Results in a minor improvement in speed.
            cell.className = "myclass";
        }

        row.appendChild(cell);
    }

    j = 100;
}

// appending the table to the fragement after it's built means we don't modify the dom with each iteration of the below loops--this is 
// probably the single largest improvement in speed
fragment.appendChild(table);

答案 2 :(得分:0)

您可以使用

var inner_text = "<table><tbody>";
while(i--) {
    var row = "";
    row += "<tr> ";

    while(j--) {


        if(j !== 0) {
           row +='<td ' + 'id="' + ["row", i, "col", (j - 1)].join("") +'"class="myClass"></td>';
        }else{
         row +='<td>' + '</td>';
        }

    }
 row +=" </tr>";
    inner_text +=row; 
    j = 100;
}
inner_text +="</tbody></table>";

这将减少制作新元素的时间,追加孩子。 希望它能帮到你

相关问题