注入html行模板的最佳方法

时间:2013-09-10 16:19:39

标签: javascript jquery html performance

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

然后,我创建了一些包含每行的数据的html代码,如下所示。

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

这似乎很慢,特别是在移动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");
  })
;

2 个答案:

答案 0 :(得分:4)

这是缓慢的原因DATA.games可能很大,而你正在呼叫(好的,缓存的)$("#gameslist")
 但是你在每次循环迭代时都使用append()

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

附加一次

在这里,我创建了一个 live demo 来向您展示最大的差异:

仅适用于 1000 次迭代,且HTML复杂度仅为 4 元素/迭代
在圈内使用.append() = ~100ms
仅使用.append()一次(循环后)= ~30ms

  

for loop中的两项测试......这只是以正确的方式/位置使用.append()

现在回到$.each和好for之间的速度差异,我发现了一个有趣的jsPerf:

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

答案 1 :(得分:3)

你在每次迭代时修改DOM,如果你只修改一次DOM,它会大大加快它的速度。在迭代时使用片段来保存元素,然后在结尾处一次性地追加它们:

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);