Fast way to dynamically fill table with data from JSON in JavaScript

前端 未结 3 1238
轻奢々
轻奢々 2020-12-12 22:52

I am experimenting with jQuery, JSON etc. and came across following task. I have a loader script on the server which returns table data in JSON format. When received the JSO

3条回答
  •  甜味超标
    2020-12-12 23:39

    Try deferring the addition of the table to the running DOM until as late as possible.

    var table = $('');   // create a new table
    
    // populate the rows
    ....  .append(table);
    
    // replace the existing table all in one go
    $('#dataTable').replaceWith(table);
    

    This should prevent any page layout until the whole table is ready.

    If performance is a real problem I'd also avoid calling methods that require parsing strings, like all those $('

    ') calls. For a single element the overhead of that is probably quite expensive (although it's worth it if you have a long string of HTML).

    As I understand it, adding large strings of tags using .append() or .html() is supposed to be pretty efficient. What you lose is the control that you would have if you had used .text() to fill the table cells to avoid HTML code injection.

    提交回复
    热议问题