Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to inject a html row template

I have a large amount of datarows in a json file which i load via ajax.

I then create quite some html code containing some of the data for each row like this.

var gl = $("#gameslist");
$.each(DATA.games, function(index, value) {
  gl.append( '<div>... lots of html code here ... '+value.somedata+'</div>');
}

this seems to be quite slow, especially on the mobile safari browser. are there any tricks or jquery plugins to speed this up?

edit: as requested, here is the ajax call:

$.ajax({
  dataType: "json",
  url: "../games.json"
})
.done(function(gamesjson){
    DATA = gamesjson;
    buildPage(); // this one is calling the above code
  })
.fail(function(){
    console.log("games.json error");
  })
;
like image 814
clamp Avatar asked Sep 10 '13 16:09

clamp


2 Answers

It's slow cause DATA.games can be huge, and you're calling (ok, a cached) $("#gameslist")
but you're using append() for every loop iteration.

To speed up things, create a variable that will hold the string representation of your HTML (containing DIVs and the data) , than inside a for loop append to string using += than once the loop is over append only once to your $("#gameslist")

Here I created a live demo to show you the drastic difference:

For only 1000 iterations and a HTML complexity of only 4 elements/iteration
Using .append() inside loop                  = ~100ms
Using .append() only once (after loop) = ~30ms

Both tests in for loop... That was all just about using .append() in the right way / place.

Now back about the differences in speed between $.each and the good old for, I've found an interesting jsPerf:

http://jsperf.com/browser-diet-jquery-each-vs-for-loop (Note: higher is better)


Memo: Test snippet:
var initialTime = new Date().getTime();

for(var i=0; i<10000; i++){
   // your code
}

console.log( new Date.getTime() - initialTime ); // ms
like image 198
Roko C. Buljan Avatar answered Oct 27 '22 19:10

Roko C. Buljan


You're modifying the DOM on every iteration, if you only modify the DOM once instead it will speed it up considerably. Use a fragment to hold the elements while iterating, then append them all at once at the end :

var gl = document.createDocumentFragment();

$.each(DATA.games, function(index, value) {
    var div  = document.createElement('div'),
        text = document.createTextNode('... lots of html code here ... '+value.somedata);

    gl.appendChild(div.appendChild(text));
}

$("#gameslist").append(gl);
like image 3
adeneo Avatar answered Oct 27 '22 18:10

adeneo