SlideShare a Scribd company logo
Optimizing Angular Performance in Enterprise Single Page Apps
Optimizing Angular
Performance
Morgan Stone
@morganstone
Render Time
Tools: ng-stats
Optimizing Angular Performance in Enterprise Single Page Apps
Optimizing Angular Performance in Enterprise Single Page Apps
Optimizing Angular Performance in Enterprise Single Page Apps
STRATEGY:
Minimize/Avoid
Watchers
$watch
scope.$watch('name', function(newValue, oldValue) {
scope.counter = scope.counter + 1;
});
where watches are set
$scope.$watch
{{ }} type bindings (ng-bind too)
Most directives (i.e. ng-show)
Scope variables scope: { bar: '='}
Filters {{ value | myFilter }}
ng-repeat
http://www.alexkras.com/11-tips-to-improve-angularjs-performance/
digest cycle runs on
User action (ng-click etc). Most built in directives will call $scope.apply upon
completion which triggers the digest cycle.
ng-change
ng-model
$http events (so all ajax calls)
$q promises resolved
$timeout
$interval
Manual call to $scope.apply and $scope.digest
http://www.alexkras.com/11-tips-to-improve-angularjs-performance/
ng-if instead of ng-show
<div class="panel" ng-show="panel.isOpen" ng-repeat="panel in panels">
{{panel.name}}
<div class="checkbox" ng-repeat="setting in panel.settings">
<label>
<input type="checkbox" ng-model="setting.on"/>
{{setting.name}}
</label>
</div>
</div>
ng-if instead of ng-show
<div class="panel" ng-show="panel.isOpen" ng-repeat="panel in panels">
{{panel.name}}
<div class="checkbox" ng-repeat="setting in panel.settings">
<label>
<input type="checkbox" ng-model="setting.on"/>
{{setting.name}}
</label>
</div>
</div>
With ng-show, the nodes
remain in the DOM and
are being watched
ng-if instead of ng-show
<div class="panel" ng-if="panel.isOpen" ng-repeat="panel in panels">
{{panel.name}}
<div class="checkbox" ng-repeat="setting in panel.settings">
<label>
<input type="checkbox" ng-model="setting.on"/>
{{setting.name}}
</label>
</div>
</div>
With ng-if, only
nodes visible will
be watched
Bind once
<p>
{{ vm.user }}
</p>
Bind once
<p>
{{ ::vm.user }}
</p>
Once the value is defined,
Angular will render it and
unbind it from the watchers
STRATEGY:
Reduce digest cycle time
track by
<div ng-repeat="model in collection | orderBy: 'id' as
filtered_result">
{{model.name}}
</div>
Optimizing Angular Performance in Enterprise Single Page Apps
http://blog.500tech.com/is-reactjs-fast/
Original:
http://speed.examples.500tech.com/ngrepeat/before/angular.html
Adding track by
http://speed.examples.500tech.com/ngrepeat/after/angular.html
track by
<div ng-repeat="model in collection | orderBy: 'id' as
filtered_result">
{{model.name}}
</div>
Without track by ng-repeat
rebuilds all the DOM nodes,
including nodes that
require no change
track by
<div ng-repeat="model in collection | orderBy: 'id' as
filtered_result track by model.id">
{{model.name}}
</div>
track by provides an
index Angular can use
to track model changes
track by
<div ng-repeat="model in collection | orderBy: 'id' as
filtered_result track by model.id">
{{model.name}}
</div>
track by must
be last in the
expression
track by
<div ng-repeat="model in collection | orderBy: 'id' as
filtered_result track by $index">
{{model.name}}
</div>
track by $index
can also provide a
performance boost
piped | filters
ng-repeat=”person in listOfFriends | filter:{
available: true}”
{{ person.birthday | date }}
Angular runs every
single piped filter twice
per $digest cycle
<div class="list-group">
<div
class="list-group-item"
ng-repeat="person in listOfFriends | filter:{ available: true}">
<div class="row">
<div class="col-sm-6">
{{person.name}}
</div>
<div class="col-sm-6">
{{person.birthday | date: 'shortDate' }}
</div>
</div>
</div>
</div>
<div class="list-group">
<div
class="list-group-item"
ng-repeat="person in listOfFriends | filter:{ available: true}">
<div class="row">
<div class="col-sm-6">
{{person.name}}
</div>
<div class="col-sm-6">
{{person.birthday | date: 'shortDate' }}
</div>
</div>
</div>
</div>
Could be done in
controller or
better yet a
service
Keep your controllers
small & leverage
services to do the
heavy lifting
angular
.module('app')
.factory('friendsService', friendsService);
friendsService.$inject = ['$http', '$filter'];
function friendsService($http, $filter) {
var factory = {
getFriends: getFriends,
getAvailableFriends: getAvailableFriends
};
return factory;
function getFriends() {
return $http.get('/someUrl', config)
Injecting $filter
getFriends: getFriends,
getAvailableFriends: getAvailableFriends
};
return factory;
function getFriends() {
return $http.get('/someUrl', config)
.then(successCallback);
function successCallback(friends) {
return friends.map(function(friend) {
friend.birthday = $filter('date')(friend.birthday, 'shortDate');
return friend;
});
}
}
Filter it one place…
in the service
function successCallback(friends) {
return friends.map(function(friend) {
friend.birthday = $filter('date')(friend.birthday, 'shortDate');
return friend;
});
}
}
function getAvailableFriends() {
return getFriends.then(function(friends) {
return friends.filter(function(friend) {
return friend.available;
});
})
}
}
Create additional
methods for
common ng-repeat
| filters
Load Time
STRATEGY:
Reduce # of requests
Optimizing Angular Performance in Enterprise Single Page Apps
Caching
$http.get(url, { cache: true}).success(...);
angular.module('docsIsolateScopeDirective', []).directive('myCustomer',
function() {
return {
restrict: 'E',
scope: {
customerInfo: '=info'
},
templateUrl: 'my-customer-iso.html'
};
});
angular.module('docsIsolateScopeDirective', []).directive('myCustomer',
function() {
return {
restrict: 'E',
scope: {
customerInfo: '=info'
},
templateUrl: 'my-customer-iso.html'
};
});
Each directive
templateUrl results
in another request
ui.router
angular.module('abcApp', ['ui.router']).config(function ($stateProvider) {
$stateProvider
.state('user.add', {
url: '/mgt/user/add', templateUrl: 'views/mgt_user/add.html'
})
.state('user.view', {
url: '/mgt/user/view/:userId', templateUrl: 'views/mgt_user/view.html'
})
.state('user.list', {
url: '/mgt/user/list', templateUrl: 'views/mgt_user/list.html'
});
});
and maybe another request
<div class="slide-animate" ng-include="template.url"></div>
which may trigger
another request
Even though template
requests are cached after
GET, they really start to
add up, especially on the
initial load of the app
Optimizing Angular Performance in Enterprise Single Page Apps
<script
type="text/ng-template"
id="templateId.html">
<p>This is the content of the template</p>
</script>
You could do this...
But this is ugly and unmaintainable
var myApp = angular.module('myApp', []);
myApp.run(function($templateCache) {
$templateCache.put('templateId.html', 'This is the content of the template');
});
$templateCache
Optimizing Angular Performance in Enterprise Single Page Apps
Sorry gramps
But we’re gonna
Javascript our HTMLs
in the BUILD.
Standard Angular build process
Concat & minify all Javascript files into a single file
Combine and minify CSS files into a single file
Gzip & cache assets
Standard Angular build process
Concat & minify all Javascript files into a single file
Combine and minify CSS files into a single file
Gzip & cache assets
Store HTML files into $templateCache
ngHtml2JS
var ngHtml2Js = require('gulp-ng-html2js');
var gulpConcat = require('gulp-concat');
gulp.task('createTemplates', function(cb){
gulp.src(['/app/**/*.html', '/app/**/*.svg'])
.pipe(ngHtml2Js({
base: '/',
moduleName: 'app',
prefix: '/'
}))
.pipe(gulpConcat('templates.'))
.pipe(gulp.dest('./services'))
.on('end', cb);
});
ngHtml2JS
angular.module("app").run(["$templateCache", function ($templateCache) {
$templateCache.put("template/modal/backdrop.html",
"<div class="modal-backdrop fade"n" +
" ng-class="{in: animate}"n" +
" ng-style="{'z-index': 1040 + (index && 1 || 0) + index*10}"n" +
"></div>n" +
"");
}]);
Thank you
mstone@designbymorgan.com
@morganstone

More Related Content

PPTX
Pengenalan blaast platform sdk
PPTX
AngularJS Routing
PDF
Angular js routing options
PPTX
AngularJS $Provide Service
PPTX
AngularJS Services
PPTX
Building an End-to-End AngularJS Application
PDF
jQuery and Rails, Sitting in a Tree
PPTX
AngularJS - $http & $resource Services
Pengenalan blaast platform sdk
AngularJS Routing
Angular js routing options
AngularJS $Provide Service
AngularJS Services
Building an End-to-End AngularJS Application
jQuery and Rails, Sitting in a Tree
AngularJS - $http & $resource Services

What's hot (20)

PPTX
AngularJS Compile Process
PDF
Angular JS Routing
PPTX
Big Data for each one of us
PDF
Django Class-based views (Slovenian)
PPTX
PDF
Backbone Basics with Examples
PPTX
Magento Dependency Injection
PPTX
Knockoutjs UG meeting presentation
PPTX
AngulrJS Overview
PPTX
Dive into AngularJS Routing
KEY
Advanced jQuery
PPTX
Dart and AngularDart
PDF
Cyclejs introduction
PDF
(PHPers Wrocław #5) How to write valuable unit test?
PPTX
Nodejs do teste de unidade ao de integração
PDF
Introduction to Web Components
PDF
How I started to love design patterns
PDF
WordCamp Montreal 2015: Combining Custom Post Types, Fields, and Meta Boxes t...
PDF
Symfony CoP: Form component
PPTX
AngularJS $http Interceptors (Explanation and Examples)
AngularJS Compile Process
Angular JS Routing
Big Data for each one of us
Django Class-based views (Slovenian)
Backbone Basics with Examples
Magento Dependency Injection
Knockoutjs UG meeting presentation
AngulrJS Overview
Dive into AngularJS Routing
Advanced jQuery
Dart and AngularDart
Cyclejs introduction
(PHPers Wrocław #5) How to write valuable unit test?
Nodejs do teste de unidade ao de integração
Introduction to Web Components
How I started to love design patterns
WordCamp Montreal 2015: Combining Custom Post Types, Fields, and Meta Boxes t...
Symfony CoP: Form component
AngularJS $http Interceptors (Explanation and Examples)
Ad

Similar to Optimizing Angular Performance in Enterprise Single Page Apps (20)

PPT
Angular js meetup
PPT
angularjsmeetup-150303044616-conversion-gate01
PDF
AngularJS - Overcoming performance issues. Limits.
PDF
Dragos Rusu - Angular JS - Overcoming Performance Issues - CodeCamp-10-may-2014
PPTX
Dive into Angular, part 3: Performance
PPTX
Optimizing a large angular application (ng conf)
PPTX
Bhuvi ppt zerobug
PDF
AngularJS performance & production tips
PDF
Introduction to AngularJS
PDF
Hey, I just met AngularJS, and this is crazy, so here’s my JavaScript, let’s ...
PPTX
AngularJS Best Practices
PPTX
Angular js performance improvements
PPTX
Angularjs Performance
PPTX
Angular Workshop_Sarajevo2
PPTX
AngularJS.part1
PDF
Javascript Memory leaks and Performance & Angular
PDF
Angular js is the future. maybe. @ ConFoo 2014 in Montreal (CA)
PPTX
01 startoff angularjs
PDF
Optimizing AngularJS Application
PDF
AngularJS in practice
Angular js meetup
angularjsmeetup-150303044616-conversion-gate01
AngularJS - Overcoming performance issues. Limits.
Dragos Rusu - Angular JS - Overcoming Performance Issues - CodeCamp-10-may-2014
Dive into Angular, part 3: Performance
Optimizing a large angular application (ng conf)
Bhuvi ppt zerobug
AngularJS performance & production tips
Introduction to AngularJS
Hey, I just met AngularJS, and this is crazy, so here’s my JavaScript, let’s ...
AngularJS Best Practices
Angular js performance improvements
Angularjs Performance
Angular Workshop_Sarajevo2
AngularJS.part1
Javascript Memory leaks and Performance & Angular
Angular js is the future. maybe. @ ConFoo 2014 in Montreal (CA)
01 startoff angularjs
Optimizing AngularJS Application
AngularJS in practice
Ad

Recently uploaded (20)

PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Spectroscopy.pptx food analysis technology
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
cuic standard and advanced reporting.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Empathic Computing: Creating Shared Understanding
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
Tartificialntelligence_presentation.pptx
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Network Security Unit 5.pdf for BCA BBA.
MYSQL Presentation for SQL database connectivity
Spectroscopy.pptx food analysis technology
Encapsulation_ Review paper, used for researhc scholars
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
cuic standard and advanced reporting.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
“AI and Expert System Decision Support & Business Intelligence Systems”
Empathic Computing: Creating Shared Understanding
The Rise and Fall of 3GPP – Time for a Sabbatical?
Programs and apps: productivity, graphics, security and other tools
Reach Out and Touch Someone: Haptics and Empathic Computing
Building Integrated photovoltaic BIPV_UPV.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Tartificialntelligence_presentation.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf
Spectral efficient network and resource selection model in 5G networks
Group 1 Presentation -Planning and Decision Making .pptx
Accuracy of neural networks in brain wave diagnosis of schizophrenia

Optimizing Angular Performance in Enterprise Single Page Apps