Best way to insert html string template

I have a large number of datarows in a json file that I upload via ajax.

Then I create some pretty html code containing some data for every line like this.

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

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

edit: on request, 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"); }) ; 
+6
source share
2 answers

This is a slow reason. DATA.games can be huge and you call (ok, cached) $("#gameslist")
but you use append() for each iteration of the loop.

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

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

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

Both tests in for loop ... This is just using .append() in the right direction / place.

Now about the speed differences between $.each and the old old for , I found an interesting jsPerf:

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


Note: Test fragment:
 var initialTime = new Date().getTime(); for(var i=0; i<10000; i++){ // your code } console.log( new Date.getTime() - initialTime ); // ms 
+4
source

You change the DOM at each iteration, if you only modify the DOM once, and that will speed it up significantly. Use the snippet to hold the elements during iteration, then add 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); 
+3
source

Source: https://habr.com/ru/post/953580/


All Articles