Angular Performance Tips


Optimize ng-repeat


// don't do this
<div ng-repeat="item in myLongList">
{{ item.property }}
</div>

// use track by!
<div ng-repeat="item in myLongList track by item.id">
{{ item.property }}
</div>

What does track by actually do? When myLongList is re-rendered, Angular does not have to rebuild an element which has already been rendered. This speeds up the cycle and avoids useless DOM manipulation.

Filters are something to also be avoided as much as possible when using within a loop.

ng-bind is better than {{}}


like this :

<div>

Hello, {{variable}}

</div>

This means that the whole text "Hello, {{variable}}" enclosed by < div > will be copied and stored in memory .

If you do something like this :

<div>

Hello, <span ng-bind="variable"></span>

</div>

That will only stored the value of variable in memory , angular will register a watcher where the watch expression consists of the variable only.

{{}}

Example:-      

name is JS object or some variable we are referring to.

It makes your template very readable i.e Anyone going through a code such as {{ name }} can easily understand that "name"  is a variable bounded to the DOM.

Drawbacks of {{}}

Sometimes when we  load our application in the browser , we can notice flashing content for some milliseconds before {{ name }} is resolved and data is loaded.


Flashing content

This happens because the template is loaded before AngularJS had a chance to go in and compile the elements. To resolve this issue, you can use ng-cloak directive.

ng-bind is used inside an HTML DOM element:

Example:-

We are using the same expression which we used for double curly brackets.

The major difference between ng-bind and {{}} is that ng-bind creates a watcher for variable passed to it(i.e. name as in above example), while curly brackets({{}}) will (store the entire expression in memory i.e. }perform dirty-checking and refreshing the expression in every digest cycle even if it is not required.

ng-bind will only apply when the value passed is changing actually.

In the first approach(i.e. {{}}), AngularJS evaluates the expression then replaces it with some value which sometime be left with the flashing double curly brackets but ng-bind saves this time by informing AngularJS to put the contents of the expression within the element itself.

Note:-

{{}} sometimes cause performance issue if we have thousand of bindings in our page.In these scenario's, we should go with ng-bind.



For some modules, like translate module is implemented  or having binding which are not going to change , make the practice to use :: (double colon) before our binding. Example

<h2 translate> load.partial.root.SUBHEADER</h2> Use this one instead of

<h1>{{ 'load.partial.root.HEADER' | translate }}</h1>


Ng-if or ng-switch instead of ng-show





Comments

Popular posts from this blog

TypeScrpt basics

font-face HTTPS issue fixes