6

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

然后我创建了相当多的 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");
  })
;
4

2 回答 2

4

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

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

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

1000次迭代和仅4 个元素/迭代的 HTML 复杂性
使用.append()内部循环 = ~100ms
仅 使用.append()一次(循环后)= ~30ms

这两项测试都在for loop......这只是关于.append()以正确的方式/地点使用。

现在回过头来谈谈和旧版本之间的速度差异,我发现了一个有趣的 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
于 2013-09-10T16:26:49.833 回答
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);
于 2013-09-10T16:28:57.530 回答