加速 Angular $compile 函数 [英] Speeding up Angular $compile function
问题描述
我正在针对新范围手动编译模板:
I'm manually compiling a template against a new scope:
var scope = _.assign($rootScope.$new(true), {
foo: 1,
bar: 2
})
var element = angular.element('<my-element foo="foo" bar="bar"></my-element>')
$compile(element)(scope)
element.appendTo(container)
在运行基本配置文件后,这段代码中最慢的部分是 $compile
,每次编译需要大约 1 毫秒.当用户滚动时,我需要一次编译大约 100 个元素.
After running a basic profile, the slowest part of this code is $compile
, which takes ~1ms per compilation. I need to compile ~100 elements at a time, as the user scrolls.
我可以应用很多优化来加速编译在第一轮 $compiles 之后,但我想加快第一轮 100 次编译.我还想将模板保留在 Angularland 中,并避免注入原始 HTML.
There are a lot of optimizations I can apply to speed up compilations after the 1st round of $compiles, but I'd like to speed up the very 1st round of 100 compiles. I'd also like to keep the templates in Angularland, and avoid injecting raw HTML.
怎么样?
从下面复制+粘贴我的评论,以便将来看到此线程的任何人都能看到:
Copy+pasting my comment from below here for visibility for anyone that sees this thread in the future:
好的,终于说得通了.如果您将函数作为第二个参数传递给 $link,angular 将为您克隆节点.如果不这样做,它将在每次调用 $link 时重用同一个节点.无论哪种方式,您都可以同步(作为 $link 的返回值)和异步(在您的回调中)访问返回的节点.这是一个设计糟糕的 API,我在 Angular 的问题跟踪器中提交了一个问题 - github.com/angular/angular.js/issues/11824
Ok, it finally makes sense. If you pass in a function as a 2nd argument to $link, angular will clone the node for you. If you don't, it will reuse the same node on every call to $link. Either way, you can access the returned node both synchronously (as the return value of $link) and asynchronously (within your callback). This is a poorly designed API, I filed an issue in Angular's issue tracker here - github.com/angular/angular.js/issues/11824
推荐答案
如果元素的结构相同,只是它们链接的作用域不同,那么你应该$compile
模板一次,然后link
100 个元素中的每一个都针对它们各自的作用域.
If the elements are of the same structure and only differ in the scope against which they are linked, then you should $compile
the template once and then link
each of the 100 elements against their respective scopes.
var myElement = angular.element('<my-element foo="foo" bar="bar"></my-element>');
var myElementLinkFn = $compile(myElement);
// "items" here is the data that drives the creation of myElement elements
angular.forEach(items, function(item){
var newScope = $scope.$new(true);
newScope.foo = item.foo;
newScope.bar = item.bar;
myElementLinkFn(newScope, function(clone){
container.append(clone);
})
});
这篇关于加速 Angular $compile 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!