jQuery append is taking too much time when repeated 500 times

Viewed 418

I have this code

$.getJSON( "https://domain.ltd/parse_data.php", function( data_recieved ) {
  if (data_recieved.length) {   
    $.each(data_recieved, function(index, element) {
      $( ".items" ).append( '<span>' + element.name +  ' = ' + element.amount + '</span><br />' );
    });
  }
})

As you can see, it's parsing json and displaying results with append. However, if there are 500 rows of data in the response, it can take up to 30 seconds to append all 500 lines. And while it's happening, the website is unresponsive.

Not only that, my CPU usage goes to 50%.

Am I doing it wrong? Maybe there is a more efficient way to parse through this much data and display it dynamicaly with jQuery?

2 Answers

I believe this to be a better solution

$.getJSON( "https://domain.ltd/parse_data.php", function( data_recieved ) {
  if (data_recieved.length) {   
    var spns = '';
    $.each(data_recieved, function(index, element) {
spns+='<span>' + element.name +  ' = ' + element.amount + '</span><br />'; 
    });
        $( ".items" ).append(spns); // or use .html();
  }
})

It seems like your DOM tree is deep & $( ".items" ) inside the loop is getting expensive.

You could improve your code so that the performance is better. At the bottom of the code I have applied and described a few tips. You can see the used time in the developer console of this page.

// just for simulating your JSON
var dataRecieved = [];

for (var i = 0; i < 500; i++) {
  dataRecieved.push({ name: 'Element ' + i, amount: parseInt(Math.random() * i) });
}

// $.getJSON( "https://domain.ltd/parse_data.php", function( data_recieved ) {
// optimization start here
console.time('test');

// use a simple for loop and save the length of received data
var element, dataReceivedLength = dataRecieved.length;

// create a variable and append all html to it
var dataMarkup = '';

// if you want to do it on only one element, use the id as selector.
// save the object to a variable
var $items = $('#first-collection');

// check if $items exist
if ($items.length && dataReceivedLength) {
  for (var i = 0; i < dataReceivedLength; i++) {
    element = dataRecieved[i];
    dataMarkup += '<span>' + element.name + ' = ' + element.amount + '</span><br />';
  }
  
  // use html() instead of append() for performance reasons in this case
  $items.html(dataMarkup);
}

console.timeLog('test');
// });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p id="first-collection" class="items"></p>

Related