gpt4 book ai didi

javascript - ng-repeat 和指令的 Angular 性能问题

转载 作者:行者123 更新时间:2023-11-27 23:47:32 25 4
gpt4 key购买 nike

我目前正在处理一个有 500 行的表。每行有 5 个单元格。每个单元格都是一个指令。呈现此表大约需要 3 秒,并且会锁定浏览器。

Timeline

99% 的时间花在“解析 HTML”函数上,我假设它解析 HTML 以获取指令。 (向下滚动时有很多 Parse HTML 函数。我猜它在 2500 左右,找不到计算方法)。

一个 plnkr 链接,您可以在其中使用 chrome 开发工具查看问题(大部分时间用于解析 HTML):http://plnkr.co/edit/UouSapMYGgCNy7jEhlR6?p=preview

如果不手动为每一行连接 HTML 字符串,我将如何优化它。

       // Code goes here
angular
.module('app', [])
.directive('cellOne', function() {
return {
scope: {
data: '='
},
templateUrl: 'cell.html'
};
})
.directive('cellTwo', function() {
return {
scope: {
data: '='
},
templateUrl: 'cell2.html'
};
})
.directive('row', function($compile) {
return {
compile: function compile() {
return {
pre: function preLink(scope, element) {

var html = '';
html += '<cell-one data=row[0]></cell-one>'
html += '<cell-two data=row[1]></cell-two>'
html += '<cell-one data=row[2]></cell-one>'
html += '<cell-two data=row[3]></cell-two>'
html += '<cell-two data=row[4]></cell-two>'
var el = angular.element(html);
var linkFunction = $compile(el);

element.append(el);
linkFunction(scope);
}
}
}
}
})
.controller('controller', function($scope) {
$scope.data = [];
// Fill the data map with random data
$scope.refresh = function() {
for (var i = 0; i < 500; ++i) {
$scope.data[i] = {};
for (var j = 0; j < 5; ++j) {
$scope.data[i][j] = Math.random();
}
}
}
$scope.refresh()
});

最佳答案

众所周知,当您拥有超过 2000 个观察者(负责处理您的数据绑定(bind))时,Angular 开始出现性能问题。在你的例子中,你至少有 2500。

减少数据绑定(bind)的数量肯定会有帮助。 Angular 最近引入了一次性数据绑定(bind),如果绑定(bind)的数据不是完全动态的,您可以利用它。

我建议看一下 Speeding up AngularJS apps with simple optimizations获取更多信息。

关于javascript - ng-repeat 和指令的 Angular 性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29082537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com