【问题标题】:Best way to inject a html row template注入 html 行模板的最佳方法
【发布时间】:2013-09-14 11:17:15
【问题描述】:

我在通过 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");
  })
;

【问题讨论】:

  • 我不知道 jQuery 是怎么做到的,但是纯 Javascript 中的 insertAdjecentHTML 可能会快得多。
  • 不要使用.each 而是使用for循环?
  • 看看这是否有帮助stackoverflow.com/questions/5361810/…
  • 你确定是这段代码很慢吗?你做了什么来查明问题?您能否向我们展示这段代码以及(可能)调用它的 AJAX 调用?
  • 嘿,如果您能找到一些确凿的方法,那就太好了,那么您能否测试(使用计时器)并发布您所做的事情。

标签: javascript jquery html performance


【解决方案1】:

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

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

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

仅适用于 1000 次迭代和只有 4 个元素/迭代的 HTML 复杂度
在循环内使用 .append()             = ~100ms
仅使用一次.append()(循环后)= ~30ms

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

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

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


备忘录: 测试 sn-p:
var initialTime = new Date().getTime();

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

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

【讨论】:

    【解决方案2】:

    您在每次迭代时都修改 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-04
      • 2018-10-20
      • 2017-04-09
      • 2012-11-12
      • 1970-01-01
      • 1970-01-01
      • 2011-06-09
      • 2010-09-23
      相关资源
      最近更新 更多