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