Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,153,517 members, 7,819,864 topics. Date: Tuesday, 07 May 2024 at 04:00 AM

Tips And Practices To Optimize Angularjs APP - Education - Nairaland

Nairaland Forum / Nairaland / General / Education / Tips And Practices To Optimize Angularjs APP (266 Views)

Knowledge, Attitude, Beliefs And Practices Of Undergraduates Concerning Abortion / Angularjs Online Training Classes And Job Assistance / Angularjs Training Provided By H2K Infosys (2) (3) (4)

(1) (Reply)

Tips And Practices To Optimize Angularjs APP by kalyanbl: 12:52pm On Apr 18, 2018
AngularJS is a magic framework. Using it well will drastically improve your productivity, code modularity and reusability. Using it badly, instead, will probably end up creating messy code and a very slow application.

Watchers

Angular’s magic, indeed, gets often abused. The most striking feature which results in slow applications is watchers.

// this code snippet creates a watcher on property
$scope.$watch("property", (new, old) => {
// do something here
});
While this is surely an exciting and powerful feature, it’s also damn slow. Or, at least, it’s slow enough to make us think: do I really need it? Do I have another way to achieve the same thing? My suggestion is: think twice. No, maybe more, but try to avoid watchers as often as possible. In my experience, they can deteriorate the application performance that much to make it unresponsive and sluggish. This is the last thing you may want for your users!

Angular’s events system, which can replace sometimes a watcher (if so, better to use them), are also to be avoided as much as possible. When you broadcast an event, indeed, the digest cycle goes through the scope hierarchy each time.

Directives

What’s some other very exciting feature in Angular? Templates, right? Well, they come at a price as well. Directives such as ng-show, ng-if, ng-repeat are just great. Yet, they handle the slowest part of our application: the DOM. While Angular provides some ways to speed up these processes, we need to be careful on the amount of stuff we put in our templates.

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.

You may not need two-way bindings

This happens more often than most think. Despite being probably the most popular feature when using Angular, two-way binding often is not needed: you can bind, instead, only one time the expressions between curly brackets in your templates by using the following syntax:

{{:: myExpression }}

ng-if vs ng-show/ng-hide

The two directives do achieve the same result but in different ways:

ng if removes/creates a node when evaluating an expression, and creates a new scope
ng-show/hide attaches a class to an element when evaluating the expression (.ng-hide { display: none !important }), and does not create a new scope
So, which one is faster? This depends on the situation. If the elements to be toggle is inside a long list, where maybe expressions get re-calculated when the scope changes, you may want to have the node removed from the DOM to avoid useless calculation. However, when often toggling an element’s visibility (a loading spinner? A button?) and is not tied to a scope, ng-show/hide might be better off.

Scope

The scope is an object containing the properties which are visible to our templates, and is defined in controllers. A controller can be populated by using the variable $scope and also by using the controller as syntax, which is the preferred way.

class Car {
constructor($scope) {
$scope.color = "red";
}
}
Car.$inject = ["$scope"];
<div ng-controller="Car">
My car's color is {{ color}}
</div>
// or, better
class Car {
constructor() {
this.color = "red";
}
}
angular.module("app"wink.
controller("Car", Car);
<div ng-controller="Car as car">
My car's color is {{ car.color}}
</div>
What’s up with the controller as syntax? What’s so special about it? Its simplicity: it’s just a plain and simple Javascript object. While this is not related to the performance, it’s a quick way to organize our controllers in a much better way.

What do we need to make sure when working with controllers and scopes? The fact that polluting the scope with useless properties and methods is just not a good idea. Indeed, the digest cycle goes through the scope hierarchy when dirty-checking: the bigger the scope, the longer the cycle, the slower your app. This means: use private methods, and expose to your scope only the things that are needed within your templates.

-- js
class Controller {
constructor(myService) {
let vm = this;
vm.getDataOnClick = () => {
getData();
};
function getData() {
myService.request().then(data => {
vm.data = data;
});
}
}
Controller.$inject = ["myService"];
angular.module("app"wink.
controller("controller", Controller);
-- html
<button ng-click="vm.getDataOnClick()">Load data</button>
Sometimes, instead, you might need the scope to be manually dirty-checked. The question here is: do you need yo go through your whole scope? Sometimes you do not, and here many people use the wrong feature. Indeed, when you need to only check the current scope (and children), you are better off using scope.$digest() than scope.$apply() as the latter will dirty-check the whole scope(internally, it runs $rootScope.digest())!

This is quite common inside directives that use, for instance, JQuery events:

...
function link() {
myPlugin.on("someEvent", (data) =>
// I need to update the directive's scope
scope.$digest(() => {
scope.data = data;
});
});
}

Use $cacheFactory to cache your data
$cacheFactory is useful when we need to store some data which can be potentially recalculated. Its usage is very straightforward and in general does not differ from how we use normal memoization.

class Controller {
constructor(cacheFactory, myService) {
let vm = this;
vm.myService = myService;
vm.cache = $cacheFactory('myCache');
vm.data = {...};
}
handleClick(someData) {
let vm = this,
cached = vm.cache.get(someData);

if (cached) {
return cached;
}
vm.data = vm.myService.heavyMethod(someData);
vm.cache.put(someData, data);
}
}

Tools for debugging

Even though Batarang is great, I prefer using ngInspector. It’s up to someone’s preference, probably, but in any case using one of those tools is extremely important to understand what is going one with the your scopes. You can find things that may be not needed, things that are repeated, and just debug things that are not working as expected. It also gives you a better understanding of the scope hierarchy.

Learn AngularJS Training Certification Course here: AngularJS Online Training

For more article visit here: https://mindmajix.com/

(1) (Reply)

Affordable Admission Into Universities In The Philippines For 2018 / Spacious And Standard Room Self Contained Apartment At Sabo, Yaba. Price: 180k / Now Available

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 18
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.