Optimizing performance in AngularJS applications is very important, especially as your app grows in size and complexity. Below are some of the main performance optimization techniques you can use,
Use one-time binding (::)
Avoid unnecessary watchers by using one-time binding when there will be no changes to the data.
<!-- Regular binding -->
<h2>{{user.name}}</h2>
<!-- One-time binding -->
<h2>{{::user.name}}</h2>
Key Point: This reduces the number of watchers and speeds up the digest cycle
Minimize Watchers
Every ng-model, ng-repeat or binding adds a
watcher. Too many watchers slow down performance.
Tips:
- Avoid deep $watch
- Remove unnecessary
ng-if,ng-show, etc. - Use static content with
ng-bindor::
Use track by in
ng-repeat
Avoid DOM re-rendering by using track by to identify the item uniquely.
<li ng-repeat="item in items track by item.id">{{item.name}}</li>
Point: This allows Angular to reuse DOM elements instead of recreating them.
Lazy Load Modules
Load only what you need using lazy loading with tools like ocLazyLoad.
// Example with ocLazyLoad
app.config(function($stateProvider) {
$stateProvider.state('dashboard', {
url: '/dashboard',
templateUrl: 'dashboard.html',
controller: 'DashboardCtrl',
resolve: {
loadModule: function($ocLazyLoad) {
return $ocLazyLoad.load('dashboardModule.js');
}
}
});
});
Limit Digest Cycle Triggers
Don't use $scope.$apply() or $timeout() unless necessary - they trigger digest cycles.
Use $scope.$applyAsync() to schedule changes without triggering an immediate digest:
$scope.$applyAsync(function() {
$scope.value = newValue;
});
Debounce ng-model for Inputs
Too many input updates slows down performance. Use ng-model-options to debounce inputs.
<input type="text" ng-model="searchText" ng-model-options="{ debounce: 300 }">
Disable Debug Info in Production
Debug data needs to be turned off to reduce memory and improve performance
app.config(['$compileProvider', function($compileProvider) {
$compileProvider.debugInfoEnabled(false);
}]);
Use track by $index cautiously
Although this is better than no tracking, it is less efficient than tracking by unique ID.
<li ng-repeat="item in items track by $index">{{item.name}}</li>
Use ng-if over
ng-show/ng-hide for Heavy DOM
ng-showplaces elements in the DOM (toggle visibility only)ng-ifadds/removes elements from the DOM (better for performance when rendering expensive components)
Use One Controller Per View
Keeping controllers centralised per view can avoid scope pollution and improve maintainability and performance.
Also, read: How to Use Location in Angularjs
Leave Comment