简体   繁体   English

为什么Handlebars.js第一次绑定后要花这么长时间?

[英]Why does Handlebars.js take so long to bind after the first time?

I have a Handlebars.js template that takes a bunch of data and renders it into a table. 我有一个Handlebars.js模板,该模板接受一堆数据并将其呈现到表中。 The first time it runs, it binds rather quickly and doesn't have any problems. 它第一次运行时,绑定速度很快,没有任何问题。 Any subsequent time, however, it takes a long time (even for the same data!) and sometimes crashes the browser. 但是,随后的任何时间都将花费很长时间(即使对于相同的数据也是如此!),有时会使浏览器崩溃。 What could be wrong? 有什么事吗

In its most generic form, the template looks like this: 以其最通用的形式,模板如下所示:

{{#each this}}
<tr>
    <td>{{data}}</td>
    ...
    <td>{{moredata}}</td>
</tr>
{{/each}}

And the binding logic in JS looks like this (very generic, again): JS中的绑定逻辑如下所示(再次非常通用):

var table = $('#mytable').empty();
$.ajax(url, data).done(function(response) {
    var template = Handlebars.compile(mytemplate);
    table.hide();
    table.html(template(response.data)); //takes a long time after the 1st time
    table.show();
});

As I said, the first time this runs, it's very quick to bind. 正如我所说,这是第一次运行,绑定很快。 The second and subsequent times, it holds up for a long time at the binding step. 第二次及以后,它将在绑定步骤中保持很长时间。

UPDATE UPDATE

So while trying to fix this, I pulled the {{each}} out of the template and appended each row in a for loop in the JS while logging the index. 因此,在尝试解决此问题时,我将{{each}}从模板中拉出,并在记录索引的同时在JS的for循环中附加了每一行。 The first run, everything binds super quick and the indexes log in a blur. 第一次运行时,所有内容都将快速绑定,并且索引会模糊记录。 The second and subsequent runs, each row takes a noticeable amount of time to bind and I can watch each index individually as the rows are being bound.... 在第二次及以后的运行中,每行都需要花费大量的时间来绑定,随着行的绑定,我可以单独观察每个索引。

After much tooling around in the jQuery source and logging of literally everything, I think I've found the culprit(s): jQuery.append() and jQuery.html() are horrifically slow. 在使用jQuery源中的大量工具并记录了几乎所有内容之后,我想我发现了罪魁祸首: jQuery.append()jQuery.html()太慢了。 By simply taking the literal HTML returned by Handlebars.js and dropping it in the DOM using .innerHTML , I was able to immensely speed up the table to near-instant rendering (coupled with .show() and .hide() to trigger only one repaint and reflow). 通过简单地把由Handlebars.js返回的HTML文本,并使用DOM删除它.innerHTML ,我能表极大加速到接近即时渲染(加上.show().hide()只触发一次重涂和重排)。 I think the issue had to be with jQuery.clone() or .cloneNode , as suggested by the Chrome profiler, but I'm not sure why that was being called in the first place. 我认为问题必须出在Chrome分析器建议的jQuery.clone().cloneNode ,但是我不确定为什么首先要调用它。

Anyways, I'll leave this here in the off chance that it helps someone. 无论如何,我会把它留在这里,以免它对某人有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM