注入html行模板的最佳方法

cla*_*amp 6 html javascript performance jquery

我在json文件中有大量的数据行,我通过ajax加载.

然后我创建了一些html代码,其中包含每行的一些数据.

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

这似乎很慢,特别是在移动Safari浏览器上.有没有任何技巧或jquery插件加快这一点?

编辑:根据要求,这是ajax调用:

$.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");
  })
;
Run Code Online (Sandbox Code Playgroud)

Rok*_*jan 4

它很慢,因为DATA.games可能很大,并且您正在调用(好吧,缓存)$("#gameslist")
但您正在使用append()每个循环迭代。

为了加快速度,创建一个变量来保存 HTML 的字符串表示形式(包含 DIV 和数据),然后在循环内for使用追加到字符串+=,而不是循环结束后仅追加一次到您的$("#gameslist")

我在这里创建了一个现场演示来向您展示巨大的差异:

仅进行1000 次迭代,HTML 复杂度仅为4 个元素/迭代
使用.append()内部循环 = ~100ms
仅 使用.append()一次(循环后)= ~30ms

两次测试for loop......这都是关于.append()以正确的方式/位置使用。

现在回到关于 jsPerf和旧版之间的速度差异,我发现了一个有趣的 jsPerf:$.eachfor

http://jsperf.com/browser-diet-jquery-each-vs-for-loop 注意:越高越好)


备注:测试片段:

var initialTime = new Date().getTime();

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

console.log( new Date.getTime() - initialTime ); // ms
Run Code Online (Sandbox Code Playgroud)