在进行了一些实验之后,我找到了一种近似估算视图渲染所需时间的方法。
场景:
- 路由到Angular应用中的页面
- 拨打AJAX以获得冗长的物品清单
- 取得项目清单,传递给
ng-repeat
ul
- 查看渲染列表
在Angular应用程序中,它
ng-repeat是一个臭名昭著的性能杀手,但它非常方便。这里是关于性能的讨论,这里。
假设我们希望获得从#3到#4的时间的近似值,因为测试AJAX调用性能非常简单。
这里是一些上下文:
<ul> <li ng-repeat="item in items"> {{item.name}} <!-- More content here --> </li></ul>在Angular控制器中:
// Get items to populate ng-repeaterMyApiService.getItems(query) .then( function (data) { $scope.items = data; // When callback finishes, Angular will process items // and prepare to load into DOM }, function (reason) { console.log(reason); });通过@runTarm,提到的事件
$routeChangeStart,
$routeChangeSuccess以及
$viewContentLoaded火灾一旦路径被加载,但在此之前的DOM渲染的项目,所以他们不解决问题。但是,通过实验,我发现AJAX回调一旦完成并设置
$scope.items,Angular就开始进行阻塞操作,以处理
items并准备将
ng-repeat
ul其插入DOM中。因此,如果您获得了AJAX调用完成之后的时间,并再次在
setTimeout回调函数中指定的时间获得时间,
setTimeout回调将排队等待直到Angular完成转发器过程,并在DOM渲染之前获得一秒钟的时间,从而为您提供了最接近的渲染时间。这不是实际的渲染时间,但是对我们来说,最慢的部分不是DOM在起作用,而是Angular,这就是我们要测量的东西。
这是修改后的示例:
// Get items to populate ng-repeaterMyApiService.getItems(query) .then( function (data) { var start = new Date(); $scope.items = data; // When callback finishes, Angular will process items // and prepare to load into DOM setTimeout( function () { // Logs when Angular is done processing repeater console.log('Process time: ' + (new Date() - start)); }); // Leave timeout empty to fire on next tick }, function (reason) { console.log(reason); });


