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

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

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

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

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?

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

edit: as requested, here is the ajax call:

编辑:根据要求,这是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 个解决方案

#1


4

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.

这很慢,因为DATA.games可能很大,而你正在调用(ok,a cached)$(“#gameslist”),但你在每次循环迭代时都使用append()。

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

为了加快速度,创建一个变量来保存HTML的字符串表示(包含DIV和数据),而不是在for循环中使用+ =附加到字符串中,而不是一旦循环结束只追加到$(“ #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

只有1000次迭代,HTML复杂度只有4个元素/迭代在循环中使用.append()= ~100ms只使用.append()一次(循环后)= ~30ms

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

for循环中的两个测试......这就是以正确的方式/位置使用.append()。

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

现在回过头来讨论$ .each和good old之间的速度差异,我发现了一个有趣的jsPerf:

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

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


Memo: Test snippet:

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

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

console.log( new Date.getTime() - initialTime ); // ms

更多相关文章

  1. 图表。js数据数组使用PHP, MySQL。如何从JSON数组定义数据源?
  2. 将JavaScript对象转换为要插入关系数据库的数组
  3. 简单数据的最佳服务器端数据存储方法
  4. JavaScript数据类型的一些注意点(2)
  5. 将对象值传递给指令而不是任何其他数据变量
  6. 如何使用Angular ng-repeat对数据进行分组?
  7. jqGrid 数据加载完事件 loadComplete 使用
  8. Angularjs指令ng-hide在单元格模板中不对网格数据的更改进行绑定
  9. 带有换行符的文本区域的数据

随机推荐

  1. 使用一个CSS选择网页外观而无需重新加载
  2. 具有相同名称的Mutiple按钮显示不同的div
  3. 在聚焦输入时,在iOS(和所有移动设备)上自定
  4. 使用bootstrap模式框的自定义选择框错误
  5. 《疯狂html5/css3/javascript讲义》这本
  6. 如果外部应用程序更改了持久模型(服务器
  7. 如何为给定的地方放置标记
  8. 如何在rails中使用ajax将数据从控制器传
  9. javascript对iframe的互操作浅析
  10. 使用ng-repeat渲染条件标记