Populating a table with 500 rows takes long - jQue

2020-07-27 03:58发布

Inspired by the comment on this question I put together a testcase.

It's populating a table with 500 rows which takes about 15 seconds in Chrome 23 on my PC. Removing the Bootstrap CSS doesn't exactly make it instant but improves the time significantly.

The actual code for adding the rows is:

$.each(response, function (idx, row) {
  var new_row = $('#row_template').clone();
  new_row.removeAttr('id');
  $('td[data-name=col1]', new_row).text(row.col1);
  $('td[data-name=col2]', new_row).text(row.col2);
  $('td[data-name=col3]', new_row).text(row.col3);
  $('td[data-name=col4]', new_row).text(row.col4);
  $('td[data-name=col5]', new_row).text(row.col5);
  $('td[data-name=col6]', new_row).text(row.col6);
  $('td[data-name=col7]', new_row).text(row.col7);
  $('td[data-name=col8]', new_row).text(row.col8);
  $('td[data-name=col9]', new_row).text(row.col9);
  $('td[data-name=col10]', new_row).text(row.col10);
  new_row.insertBefore($('#row_template')).show();
});

The abolutely lowest execution time I would probably get by concatenating HTML and getElementById().innerHTML, but can I do any other obvious optimizations while still maintaining some ease of use (especially getting the row from the template)?

2条回答
▲ chillily
2楼-- · 2020-07-27 04:33

It is only slow when you do it while the table is visible. If you hide it before and show it again after the changes it is quite fast:

$('#results').hide();

$.each(response, function (idx, row) {
  ...
});

$('#results').show();

Check out my solution here: http://smartk8.no-ip.org/stackoverflow/13537578.htm

查看更多
狗以群分
3楼-- · 2020-07-27 04:45

Don't add each row - it means redrawing 500 times. Add them to one string of html and add that to your page. example: http://jsfiddle.net/yLSy9/

<button id="addmany">Add one at a time</button>
<button id="addonce">Conact then add</button>
<table>
</table>​

jQ:

$('#addmany').on('click', function(){

    for (i=0; i<5000; i++)
    {
        var row=$('<tr><td>test</td></tr>');
        row.appendTo('table');
    }
});

$('#addonce').on('click', function(){
    rows='';
    for (i=0; i<5000; i++)
    {
        var row='<tr><td>test</td></tr>';
        rows=rows+row;
    }
    $(rows).appendTo('table');
});

​
查看更多
登录 后发表回答