Dynamic creation of large html table in javascript performance

前端 未结 7 1310
轻奢々
轻奢々 2020-12-02 23:30

I have an application which is used for data analysis and I\'m having a few performance issues with the creation of the table. The data is extracted from documents and it is

相关标签:
7条回答
  • 2020-12-03 00:32

    joinHi,

    The rendering is a problem, but there is also a problem with concatenating so many strings inside the loop, especially once the string gets very large. It would probably be best to put the strings into individual elements of an array then finally use "join" to create the huge string in one fell swoop. e.g.

    var r = new Array();
    var j = -1, recordId;
    r[++j] =  '<table><thead><tr><th>ID</th><th>Status</th><th>Name</th><th>Actions</th><th>Origin</th></tr></thead><tbody>'; 
    for (var i in data){
        var d = data[i];
        recordId = d.id;
        r[++j] = '<tr id="';
        r[++j] = recordId;
        r[++j] = '" class="';
        r[++j] = d.status;
        r[++j] = '"><td width="1%" align="center">';
        r[++j] = recordId;
        r[++j] = '</td><td width="1%" align="center"><span class="status" rel="';
        r[++j] = recordId;
        r[++j] = '"><strong>';
        r[++j] = d.status;
        r[++j] = '</strong></span></td><td width="70%"><span class="name">';
        r[++j] = d.name;
        r[++j] = '</span></td><td width="2%"><input type="button" class="failOne" rev="';
        r[++j] = recordId;
        r[++j] = '" value="F"><input type="button" class="promoteOne" rev="';
        r[++j] = recordId;
        r[++j] = '" value="P"></td><td width="1%">';
        r[++j] = d.origin;
        r[++j] = '</td></tr>';
    }
    r[++j] = '</tbody></table>';
    $('#documentRows').html(r.join(''));
    

    Also, I would use the array indexing method shown here, rather than using "push" since, for all browsers except Google Chrome it is faster, according to this article.

    0 讨论(0)
提交回复
热议问题