Uncategorized

Angular JS App Performance Improvement with Bindonce

14 December 2016

Angular uses dirty checking to keep track of all the changes in the app. It will have to go through every watcher to check if they need to be updated. It will continue this process until all of the watchers have been updated and app has stabilized. If there are more than 2000 watchers, it can lag the UI, and this number can be reached easily if we don’t pay attention to the data binding. For example,

<ul>
<li ng-nGpeat=“product in ProductList”>
<div ng-if=“product.Available”>
<span ng-class=”{‘error’:product.IsError}”
ng-bind=”product. Name”X/span>
<im& ng-src=”{{prodt^ct^Jjria^ }”>
</div>
</li>
</ul>

Angular internally creates a $watch for each ng-* directive. In the above example, for displaying one product info, it created 4 + 1 (ngRepeatWatch) watchers for product. If there are 100 products, it will create 401 watchers. As this is static data we don’t want to watch this product data, but whenever an action triggered angular digest cycle starts and checks for all these 401 watchers, that is where BINDONCE library helps.
With the Bindonce we can modify the above example as illustrated below –

<ul>
<li bindonce ng-repeat=“product in ProductList”>
<div bo-if=“product.Available”>
<span bo-class=“{‘error’:product.IsError}”
bo-bind=”product.Name”></span>
<img bo-src=”{{product.imageUrl}}”>
</div>
</li>
</ul>

This uses only 1 watcher for ng-repeat.

If the ProductList is dynamic data and we want to rebind the UI dynamically without adding watchers Bindonce provides bo-refresh-on.

<ul>
<li bindonce refresh-on=”UpdateProducts”
ng-repeat=”product in ProductList”>
<div bo-if=“product.Available”>
<span bo-class=“{‘error’:product.IsError}”
bo-bind=”product.Name”></span>
<img bo-src=“{{product.imageUrl}}”>
</div>
</li>
</ul>

Whenever you want to update the ProductList, call this –
$scope.$broadcast(‘UpdateProducts’)
Every bo-* directive replaces the equivalent ng-* and works in the same way, except that it is evaluated only once.

Conclusion:
We greatly reduced the watchers by utilizing Bindonce library. There are many other such tricks to improve the Angular app performance.

Reference:
https://github.com/Pasvaz/bindonce

Author: Praveen Kumar Reddy, PreludeSys

Recent Posts