R2D2
R2D2

Reputation: 2640

how to speed up my ajax call and append to table?

I have an ajax call that calls around 1,000 rows and updates a table on my web page.

While waiting on the table to update, the page freezes for around 10 seconds - the page wont scroll, mouseovers don't work, etc.

Doing some experiments, the ajax call doesn't seem to affect the page. It appears to be the 'append' function that freezes the page.

I have read online about how to make this quicker, but without any improvement.

My original code was...

$.ajaxSetup({ async: true });
$.ajax({
  cache: false,
  url: 'ajax_addtablerows.php',
  dataType: 'json',
  success: function(data) {
  $.each(data, function (i,obj) {
    tableUpdate = '<tr><td class="col1">' + obj.col1 + '</td><td class="col2">' + obj.col2 + '</td><td class="col3">' + obj.col3 + '</td><td class="col4">' + obj.col4 + '</td></tr>';
    $('#myTable').append(tableUpdate);
  });
},
});

But I read a few SO articles that said looping the 'append' call was a bad idea, so I updated my code to this...

var tableUpdate = "";
$.ajaxSetup({ async: true });
$.ajax({
  cache: false,
  url: 'ajax_addtablerows.php',
  dataType: 'json',
  success: function(data) {
  $.each(data, function (i,obj) {
    tableUpdate += '<tr><td class="col1">' + obj.col1 + '</td><td class="col2">' + obj.col2 + '</td><td class="col3">' + obj.col3 + '</td><td class="col4">' + obj.col4 + '</td></tr>';
  });
  $('#myTable').append(tableUpdate);
},
});

And moved the 'append' outside of the 'each' loop.

But this hasn't made the expected improvement. The page still freezes for around 10 seconds while the table updates.

If I remove the line:

$('#myTable').append(tableUpdate);

Then the page doesn't freeze or slow down (but obviously the table doesn't update!)

So this leads me to believe it is the 'append' that is causing the freeze.

Any other tips to speed this up?

Upvotes: 1

Views: 398

Answers (1)

Vahid
Vahid

Reputation: 950

The fastest way i have ever tried is as following. look at this blog post:

success (data) {
    var arr = [];
    var i = 0;
    var length = data.length;
    for (var j = 0; j < length; j++) {
        arr[i++] = '<tr><td class="col1">';
        arr[i++] = data[j].col1;
        arr[i++] = </td><td class="col2">;
        arr[i++] = data[j].col2;
        arr[i++] = </td><td class="col3">;
        arr[i++] = data[j].col3;
        arr[i++] = </td><td class="col4">;
        arr[i++] = data[j].col4;
        arr[i++] = '</td></tr>';
    }
    $('#myTable').append(arr.join(''));
}

but as @charlietfl mentioned in the comments, you should probably reduce the amount of returned array from ajax call to let browser render them in a reasonable time. you may make another ajax call after processing the first batch...

Upvotes: 1

Related Questions