Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

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

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 JSON data, I want to fill my table with them. I am currently using code similar to following (there are more columns and some more advanced processing, but you got the idea):

...
for (var key=0, size=data.length; key<size;key++) {

  $('<tr>')
            .append( $('<td>').html(
                data[key][0]
            ) )
            .append( $('<td>').addClass('whatever1').html(
                data[key][1]
            ) )
            .append( $('<td>').addClass('whatever2').html(
                data[key][2]
            ) )
            .appendTo('#dataTable');
}
...

<table id="#dataTable"></table>
...

This works pretty much ok. But once the data is growing it's getting terribly slow. For few hunderts of records it take up to about 5s (Firefox, IE) to build the table and that is a bit slow. If I e.g. create the whole HTML on the server and send it as string which I include in the table it will be pretty fast.

So, is there faster way to fill the table?

NOTE: I know what is paging and I will use it in the end so please don't say "What do you need such a big table on your page for?". This question is about how to fill table quickly no matter how many records you will display :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

See my response to an earlier similar query using arrays and "join".

Don't use jQuery at all until the very end, when you call it just once. Also, cut out string concatenation as well by storing the strings in an array and using the "join" method to build the string in one go.

e.g.

 var r = new Array(), j = -1;
 for (var key=0, size=data.length; key<size; key++){
     r[++j] ='<tr><td>';
     r[++j] = data[key][0];
     r[++j] = '</td><td class="whatever1">';
     r[++j] = data[key][1];
     r[++j] = '</td><td class="whatever2">';
     r[++j] = data[key][2];
     r[++j] = '</td></tr>';
 }
 $('#dataTable').html(r.join('')); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...