Angular.js 缓存 $compiled 模板/ng-repeat 中指令的渲染性能 [英] Angular.js caching $compiled templates / rendering performance of directives inside ng-repeat

查看:41
本文介绍了Angular.js 缓存 $compiled 模板/ng-repeat 中指令的渲染性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个呈现表格单元格的指令(看看我在这里编译它的方式,基本上是在 link fn 内使用 $compile Angular.js 指令模板使用来自父/继承范围的变量),现在这在两个 ng-repeat 中使用,一个用于行,一个用于列,所以基本上是

I have a a directive which renders table cell(see how the way I'm compiling it here, basically using $compile inside link fn Angular.js directive template using variable from parent/inherited scope), now this is used inside two ng-repeats, one for rows, one for columns, so it's basically

<ng-repeat row in rows>
  <ng-repeat column in columns>
    <my-cell-directive />
  </ng-repeat>      
</ng-repeat>

有 50 行和 8 列,它对(渲染)性能产生了相当大的(无论如何都很明显)影响.

with 50 rows and 8 columns its got a pretty big(well pretty noticeable anyway) impact on (rendering) performance.

所以我一直在寻找改进它的方法.首先,我试图摆脱列的内部重复,创建一个 my-cols-directive ,它在内部迭代列,找到它们的模板,创建一个字符串(里面有 8 个列),然后编译它.这将编译量从 400 降低到 50.但它在渲染上并没有真正明显的改进(确实有,但只有大约 15%).

So I was looking for a way to improve it. Firstly I tried to get rid of that inner repeat for columns, creating a my-cols-directive which internally iterates over columns, find their template, create one string(with those 8 columns inside) and then compiles it. Which lowered amount of compiling from 400 to 50. But it didn't really have noticeable improvement on rendering(well it did, but only about 15%).

现在我的另一个想法是以某种方式将它减少到只有一个编译,基本上是在 ng-repeat 的第一次迭代中编译它,然后保存(缓存)编译的结果,以便指令将使用它而不是编译它再一次,只是用当前迭代中的绑定值替换绑定值.

Now my other idea was to reduce it to only one compile somehow, basically compiling it in the first iteration of ng-repeat, then saving(caching) the compiled result so the directive would then use this instead of compiling it over and over again, just replacing binding values with ones from the current iteration.

有可能吗?或者有什么其他方法可以提高渲染速度?

Would it be possible somehow? Or is there any other way to improve rendering speed?

推荐答案

如果可能,您应该避免在链接函数中使用 $compile.不过,您可以缓存 $compile 的部分结果.

You should avoid using $compile inside linking function if possible. You can cache parital result of the $compile though.

使用 compiled 对象的第二个参数 cloneAttachFn

Use the second argument of the compiled object cloneAttachFn

directive('lol', function($compile){
  var compiled = $compile(template);
  return function(scope, element, attr){
    compiled(scope, function(clonedElement, scope){
      element.append(clonedElement);  
    };
  }
})

示例

这篇关于Angular.js 缓存 $compiled 模板/ng-repeat 中指令的渲染性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆