SlideShare a Scribd company logo
Small computers, big performance:
Optimize your Angular
Speakers
David Barreto
Andrew Smith
Agenda
1. Ahead of Time Compilation
2. Lazy Loading
3. Change Detection
4. Memory Leaks
5. Server Side Rendering
Rangle Academy
Goal and Structure:
Program to share knowledge within the company
It follows a "workshop" structure
Usually 2 hours long
Covers hard and soft skills
Some workshops available:
Webpack
React
React Native
Google Analytics
Unit Testing
Introduction to Payment Gateways
Continuous Delivery to Production
Conflict Management
About the Demo App
Characteristics:
Built using Angular 2.4.1
Uses Angular CLI beta-26
Redux store with ngrx
Tachyons for CSS
Server side rendering with Universal
All the numbers shown are based on:
Low end device emulation (5x slowdown)
Good 3G connection emulation
Ahead of Time Compilation (AoT)
Compilation Modes
Just in Time Compilation (JiT):
Compilation performed in the browser at run time
Bigger bundle size (includes the compiler)
Takes longer to boot the app
$ ng serve --prod
Ahead of Time Compilation (AoT):
Compilation performed in the server at build time
Smaller bundle size (doesn't include the compiler)
The app boots faster
$ ng serve --prod --aot
Angular performance slides
Angular performance slides
JiT vs AoT in Demo App (Prod + Gzip)
CSS files are included in the "other js files"
File Size (JiT) Size (AoT)
main.bundle.js 6.4 KB 23.9 KB
vendor.bundle.js 255 KB 158 KB
other js files 48.7 KB 49.6 KB
Total Download 306 KB 231.5 KB
AoT goals (from the ):docs
Faster rendering => Components already compiled
Fewer async request => Inline external HTML and CSS
Smaller bundle size => No compiler shipped
Detect template errors => Because they can
Better security => Prevents script injection attack
Boot Time Comparison
Event Time (JiT) Time (AoT)
DOM Content Loaded 5.44 s 3.25 s
Load 5.46 s 3.27 s
FMP 5.49 s 3.30 s
DOM Content Loaded:
The browser has finished parsing the DOM
jQuery nostalgia => $(document).ready()
Load: All the assets has been downloaded
First Meaningful Paint (FMP):
When the user is able to see the app "live" for the first time
(Show browser profile for both modes)
Lazy Loading
What is Lazy Loading?
Ability to load modules on demand => Useful to reduce the app startup time
(Compare branches no-lazy-loading vs normal-lazy-loading )
Bundle Sizes Comparison (Prod + AoT)
File Size (No LL) Size (LL)
main.bundle.js 23.9 KB 17.4 KB
vendor.bundle.js 158 KB 158 KB
other js files 49.6 KB 49.6 KB
Initial Download 231.5 KB 225 KB
0.chunk.js - 9.1 KB
Total Download 231.5 KB 234.1 KB
Webpack creates a "chunk" for every lazy loaded module
The file 0.chunk.js is loaded when the user navigates to admin
The initial download size is smaller with LL
The total size over time is bigger with LL because of Webpack async loading
The effect of LL start to be noticeable when the app grows
Boot Time Comparison (Prod + AoT)
Event Time (No LL) Time (LL)
DOM Content Loaded 3.25 s 3.11 s
Load 3.27 s 3.25 s
FMP 3.30 s 3.16 s
Not much difference for an small app
Just one lazy loaded module with a couple of components
The impact is noticeable for big apps
How to Enable Lazy Loading? (1/4)
Step 1: Organize your code into modules
$ tree src/app -L 1
src/app
├── admin/
├── app-routing.module.ts
├── app.component.ts
├── app.module.ts
├── core/
├── public/
└── shared/
CoreModule provides all the services and the Redux store
SharedModule provides all the reusable components, directives or pipes
PublicModule provides the components and routing of the public section of the app
AdminModule provides the components and routing of the private section of the app
AppModule root module
(Show modules in the IDE)
How to Enable Lazy Loading (2/4)
Step 2: Create a routing module for lazy loaded module
const routes: Routes = [{
path: '',
component: AdminComponent,
children: [
{ path: '', redirectTo: 'list', pathMatch: 'full' },
{ path: 'list', component: WorkshopListComponent },
{ path: 'new', component: WorkshopEditorComponent },
{ path: 'edit/:id', component: WorkshopEditorComponent },
]
}];
@NgModule({
imports: [ RouterModule.forChild(routes) ],
exports: [ RouterModule ],
})
export class AdminRoutingModule {}
Always use the method forChild when importing the RouterModule
Avoids duplication of services in the child injector
How to Enable Lazy Loading (3/4)
Step 3: Define a child <router-outlet> to render child routes
@Component({
selector: 'rio-admin',
template: `
<nav>
<a routerLink="./list">List Workshops</a>
<a routerLink="./new">Create Workshop</a>
</nav>
<router-outlet></router-outlet>
`,
})
export class AdminComponent {}
How to Enable Lazy Loading (4/4)
Step 4: Use the property loadChildren to lazy load the module
export const routes: Routes = [{
path: 'admin',
loadChildren: 'app/admin/admin.module#AdminModule',
canActivate: [ AuthGuardService ],
}];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ],
})
export class AppRoutingModule {}
Only in the root module use the forRoot method of RouterModule
Never import a lazy loaded in this file, use a string as reference
The path of loadChildren is not relative to the file, but to the index.html file
(Show routes in the IDE and URL structure of the app)
Preloading
(Compare branches normal-lazy-loading vs master )
Enable Preloading
Define the property preloadingStrategy in the root module routing
import { PreloadAllModules } from '@angular/router';
export const routes: Routes = [ ... ];
@NgModule({
imports: [
RouterModule.forRoot(routes, {
preloadingStrategy: PreloadAllModules
})
],
exports: [ RouterModule ],
})
export class AppRoutingModule {}
Change Detection
What's Change Detection (CD)?
It's a mechanism to keep our "models" in sync with our "views"
Change detection is fired when...
The user interacts with the app (click, submit, etc.)
An async event is completed (setTimeout, promise, observable)
When CD is fired, Angular will check every component starting from the top once.
Change Detection Strategy: OnPush
Angular offers 2 strategies:
Default: Check the entire component when CD is fired
OnPush: Check only relevant subtrees when CD is fired
OnPush Requirements:
Component inputs ( @Input ) need to be immutable objects
@Component({
selector: 'rio-workshop',
templateUrl: './workshop.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class WorkshopComponent {
@Input() workshop: Workshop;
@Input() isSummary = false;
}
View Example
Example: The Component Tree
Default Change Detection
OnPush Change Detection
Summary
What to do?
Apply the OnPush change detection on every component*
Never mutate an object or array, always create a a new reference ( )blog
// Don't
let addPerson = (person: Person): void => {
people.push(person);
};
// Do
let addPerson = (people: Person[], person: Person): Person[] => {
return [ ...people, person ];
};
Benefits:
Fewer checks of your components during Change Detection
Improved overall app performance
Memory Leaks
What's Memory Leak?
The increase of memory usage over time
What Causes Memory Leaks in Angular?
Main Source => Subscriptions to observables never closed
@Injectable()
export class WorkshopService {
getAll(): Observable<Workshop[]> { ... }
}
@Component({
selector: 'rio-workshop-list',
template: `
<div *ngFor="let workshop of workshops">
{{ workshop.title }}
</div>`
})
export class WorkshopListComponent implements OnInit {
...
ngOnInit() {
this.service.getAll().subscribe(workshops => this.workshops = workshops);
}
}
Manually Closing Connections
Before the element is destroyed, close the connection
@Component({
selector: 'rio-workshop-list',
template: `
<div *ngFor="let workshop of workshops">
{{ workshop.title }}
</div>`
})
export class WorkshopListComponent implements OnInit, OnDestroy {
...
ngOnInit() {
this.subscription = this.service.getAll()
.subscribe(workshops => this.workshops = workshops);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
The async Pipe
It closes the connection automatically when the component is destroyed
@Component({
selector: 'rio-workshop-list',
template: `
<div *ngFor="let workshop of workshops$ | async">
{{ workshop.title }}
</div>`
})
export class WorkshopListComponent implements OnInit {
ngOnInit() {
this.workshops$ = this.service.getAll();
}
}
This is the recommended way of dealing with Observables in your template!
The Http Service
Every method of the http services ( get , post , etc.) returns an observable
Those observables emit only one value and the connection is closed automatically
They won't cause memory leak issues
@Component({
selector: 'rio-workshop-list',
template: `
<div *ngFor="let workshop of workshops">
{{ workshop.title }}
</div>`
})
export class WorkshopListComponent implements OnInit {
...
ngOnInit() {
this.http.get('some-url')
.map(data => data.json())
.subscribe(workshops => this.workshops = workshops);
}
}
Emit a Limited Number of Values
RxJs provides operators to close the connection automatically
Examples: first() and take(n)
This won't cause memory leak issues even if getAll emits multiple values
@Component({
selector: 'rio-workshop-list',
template: `
<div *ngFor="let workshop of workshops">
{{ workshop.title }}
</div>`
})
export class WorkshopListComponent implements OnInit {
ngOnInit() {
this.service.getAll().first()
.subscribe(workshops => this.workshops = workshops);
}
}
Server Side Rendering
Angular Universal
Provides the ability to pre-render your application on the server
Much faster time to first paint
Enables better SEO
Enables content preview on social networks
Fallback support for older browsers
Use the as the base of your applicationuniversal-starter
What's Included
Suite of polyfills for the server
Server rendering layer
Preboot - replays your user's interactions after Angular has bootstrapped
State Rehydration - Don't lose your place when the application loads
Boot Time Comparison (Client vs Server)
Both environments include previous AoT and Lazy Loading enhancements
Event Time (Client) Time (Server)
DOM Content Loaded 3.11 s 411 ms
Load 3.25 s 2.88 s
FMP 3.16 s ~440 ms
*Times are on mobile over 3G
Universal Caveats
Cannot directly access the DOM
constructor(element: ElementRef, renderer: Renderer) {
renderer.setElementStyle(element.nativeElement, ‘font-size’, ‘x-large’);
}
Current solutions only cover Express and ASP.NET servers
Project will be migrated into the core Angular repo for v4
Summary
Performance Changes
Event JiT AoT Lazy Loading SSR
DOM Content Loaded 5.44 s 3.25 s 3.11 s 411 ms
Load 5.46 s 3.27 s 3.25 s 2.88 s
FMP 5.46 s 3.30 s 3.16 s ~440 ms
% Improvement (FMP) 39.6% 4.3% 86.1%
*Times are on mobile over 3G
Slides
https://github.com/rangle/angular-performance-meetup

More Related Content

What's hot (20)

PDF
Spring boot introduction
Rasheed Waraich
 
PPTX
Angular Best Practices To Build Clean and Performant Web Applications
Albiorix Technology
 
PDF
Angular vs React vs Vue | Javascript Frameworks Comparison | Which One You Sh...
Edureka!
 
PPTX
Angular 2.0 forms
Eyal Vardi
 
PDF
An introduction to Vue.js
Javier Lafora Rey
 
PDF
introduction to Vue.js 3
ArezooKmn
 
PDF
Angular.pdf
Jaouad Assabbour
 
PDF
Angular 10 course_content
NAVEENSAGGAM1
 
PDF
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
PDF
Angular
Lilia Sfaxi
 
PPTX
Express JS Middleware Tutorial
Simplilearn
 
PPTX
Angular Data Binding
Jennifer Estrada
 
PPTX
React workshop
Imran Sayed
 
PPT
Angular Introduction By Surekha Gadkari
Surekha Gadkari
 
PPTX
Angular 5 presentation for beginners
Imran Qasim
 
PDF
Spring Boot
Jaran Flaath
 
DOCX
Angular Interview Questions & Answers
Ratnala Charan kumar
 
PPTX
React + Redux Introduction
Nikolaus Graf
 
PPTX
React-JS.pptx
AnmolPandita7
 
PPTX
Vue js for beginner
Chandrasekar G
 
Spring boot introduction
Rasheed Waraich
 
Angular Best Practices To Build Clean and Performant Web Applications
Albiorix Technology
 
Angular vs React vs Vue | Javascript Frameworks Comparison | Which One You Sh...
Edureka!
 
Angular 2.0 forms
Eyal Vardi
 
An introduction to Vue.js
Javier Lafora Rey
 
introduction to Vue.js 3
ArezooKmn
 
Angular.pdf
Jaouad Assabbour
 
Angular 10 course_content
NAVEENSAGGAM1
 
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
Angular
Lilia Sfaxi
 
Express JS Middleware Tutorial
Simplilearn
 
Angular Data Binding
Jennifer Estrada
 
React workshop
Imran Sayed
 
Angular Introduction By Surekha Gadkari
Surekha Gadkari
 
Angular 5 presentation for beginners
Imran Qasim
 
Spring Boot
Jaran Flaath
 
Angular Interview Questions & Answers
Ratnala Charan kumar
 
React + Redux Introduction
Nikolaus Graf
 
React-JS.pptx
AnmolPandita7
 
Vue js for beginner
Chandrasekar G
 

Viewers also liked (8)

PDF
Angular 2 Component Communication - Talk by Rob McDiarmid
Amrita Chopra
 
PDF
Angular Optimization Web Performance Meetup
David Barreto
 
PDF
Curso de AWK (David Barreto)
David Barreto
 
PDF
Metodología Scrum (Ing. David Barreto)
David Barreto
 
PDF
Mlocjs buzdin
Dmitry Buzdin
 
PPT
Robotic JavaScript
Nikolai Onken
 
PDF
GDG 2014 - RxJava를 활용한 Functional Reactive Programming
waynejo
 
PDF
reveal.js 3.0.0
Hakim El Hattab
 
Angular 2 Component Communication - Talk by Rob McDiarmid
Amrita Chopra
 
Angular Optimization Web Performance Meetup
David Barreto
 
Curso de AWK (David Barreto)
David Barreto
 
Metodología Scrum (Ing. David Barreto)
David Barreto
 
Mlocjs buzdin
Dmitry Buzdin
 
Robotic JavaScript
Nikolai Onken
 
GDG 2014 - RxJava를 활용한 Functional Reactive Programming
waynejo
 
reveal.js 3.0.0
Hakim El Hattab
 
Ad

Similar to Angular performance slides (20)

PPTX
Advanced angular
Sumit Kumar Rakshit
 
PDF
Angular - Improve Runtime performance 2019
Eliran Eliassy
 
PDF
Top 7 Angular Best Practices to Organize Your Angular App
Katy Slemon
 
PDF
Angular Interview Question & Answers PDF By ScholarHat
Scholarhat
 
PDF
Rethinking Angular Architecture & Performance
Mark Pieszak
 
PDF
How To Tweak Angular 2 Performance (JavaScript Frameworks Day 2017 Kiev)
Oleksandr Tryshchenko
 
PPTX
Александр Трищенко "How to improve Angular 2 performance?"
Fwdays
 
PDF
Step by Step Guide on Lazy Loading in Angular 11
Katy Slemon
 
PDF
8 things you didn't know about the Angular Router, you won't believe #6!
Laurent Duveau
 
PDF
Angular performance improvments
Eliran Eliassy
 
PDF
Vered Flis: Because performance matters! Architecture Next 20
CodeValue
 
PDF
Angular resolver tutorial
Katy Slemon
 
PDF
26 top angular 8 interview questions to know in 2020 [www.full stack.cafe]
Alex Ershov
 
PDF
Runtime performance
Eliran Eliassy
 
PPTX
Challenges of angular in production (Tasos Bekos) - GreeceJS #17
GreeceJS
 
PPTX
Making Angular2 lean and Fast
Vinci Rufus
 
DOCX
Angular for Beginners: A Comprehensive Guide
CMARIX TechnoLabs
 
PPT
Top 10 Angular Best Practices to Improve Your App?
Agile Infoways LLC
 
PDF
How To Tweak Angular 2 Performance
Oleksandr Tryshchenko
 
PPTX
Making Single Page Applications (SPA) faster
Boris Livshutz
 
Advanced angular
Sumit Kumar Rakshit
 
Angular - Improve Runtime performance 2019
Eliran Eliassy
 
Top 7 Angular Best Practices to Organize Your Angular App
Katy Slemon
 
Angular Interview Question & Answers PDF By ScholarHat
Scholarhat
 
Rethinking Angular Architecture & Performance
Mark Pieszak
 
How To Tweak Angular 2 Performance (JavaScript Frameworks Day 2017 Kiev)
Oleksandr Tryshchenko
 
Александр Трищенко "How to improve Angular 2 performance?"
Fwdays
 
Step by Step Guide on Lazy Loading in Angular 11
Katy Slemon
 
8 things you didn't know about the Angular Router, you won't believe #6!
Laurent Duveau
 
Angular performance improvments
Eliran Eliassy
 
Vered Flis: Because performance matters! Architecture Next 20
CodeValue
 
Angular resolver tutorial
Katy Slemon
 
26 top angular 8 interview questions to know in 2020 [www.full stack.cafe]
Alex Ershov
 
Runtime performance
Eliran Eliassy
 
Challenges of angular in production (Tasos Bekos) - GreeceJS #17
GreeceJS
 
Making Angular2 lean and Fast
Vinci Rufus
 
Angular for Beginners: A Comprehensive Guide
CMARIX TechnoLabs
 
Top 10 Angular Best Practices to Improve Your App?
Agile Infoways LLC
 
How To Tweak Angular 2 Performance
Oleksandr Tryshchenko
 
Making Single Page Applications (SPA) faster
Boris Livshutz
 
Ad

Recently uploaded (20)

PDF
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PPTX
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PPTX
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
PDF
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 

Angular performance slides

  • 1. Small computers, big performance: Optimize your Angular
  • 3. Agenda 1. Ahead of Time Compilation 2. Lazy Loading 3. Change Detection 4. Memory Leaks 5. Server Side Rendering
  • 4. Rangle Academy Goal and Structure: Program to share knowledge within the company It follows a "workshop" structure Usually 2 hours long Covers hard and soft skills Some workshops available: Webpack React React Native Google Analytics Unit Testing Introduction to Payment Gateways Continuous Delivery to Production Conflict Management
  • 5. About the Demo App Characteristics: Built using Angular 2.4.1 Uses Angular CLI beta-26 Redux store with ngrx Tachyons for CSS Server side rendering with Universal All the numbers shown are based on: Low end device emulation (5x slowdown) Good 3G connection emulation
  • 6. Ahead of Time Compilation (AoT)
  • 7. Compilation Modes Just in Time Compilation (JiT): Compilation performed in the browser at run time Bigger bundle size (includes the compiler) Takes longer to boot the app $ ng serve --prod Ahead of Time Compilation (AoT): Compilation performed in the server at build time Smaller bundle size (doesn't include the compiler) The app boots faster $ ng serve --prod --aot
  • 10. JiT vs AoT in Demo App (Prod + Gzip) CSS files are included in the "other js files" File Size (JiT) Size (AoT) main.bundle.js 6.4 KB 23.9 KB vendor.bundle.js 255 KB 158 KB other js files 48.7 KB 49.6 KB Total Download 306 KB 231.5 KB AoT goals (from the ):docs Faster rendering => Components already compiled Fewer async request => Inline external HTML and CSS Smaller bundle size => No compiler shipped Detect template errors => Because they can Better security => Prevents script injection attack
  • 11. Boot Time Comparison Event Time (JiT) Time (AoT) DOM Content Loaded 5.44 s 3.25 s Load 5.46 s 3.27 s FMP 5.49 s 3.30 s DOM Content Loaded: The browser has finished parsing the DOM jQuery nostalgia => $(document).ready() Load: All the assets has been downloaded First Meaningful Paint (FMP): When the user is able to see the app "live" for the first time (Show browser profile for both modes)
  • 13. What is Lazy Loading? Ability to load modules on demand => Useful to reduce the app startup time (Compare branches no-lazy-loading vs normal-lazy-loading )
  • 14. Bundle Sizes Comparison (Prod + AoT) File Size (No LL) Size (LL) main.bundle.js 23.9 KB 17.4 KB vendor.bundle.js 158 KB 158 KB other js files 49.6 KB 49.6 KB Initial Download 231.5 KB 225 KB 0.chunk.js - 9.1 KB Total Download 231.5 KB 234.1 KB Webpack creates a "chunk" for every lazy loaded module The file 0.chunk.js is loaded when the user navigates to admin The initial download size is smaller with LL The total size over time is bigger with LL because of Webpack async loading The effect of LL start to be noticeable when the app grows
  • 15. Boot Time Comparison (Prod + AoT) Event Time (No LL) Time (LL) DOM Content Loaded 3.25 s 3.11 s Load 3.27 s 3.25 s FMP 3.30 s 3.16 s Not much difference for an small app Just one lazy loaded module with a couple of components The impact is noticeable for big apps
  • 16. How to Enable Lazy Loading? (1/4) Step 1: Organize your code into modules $ tree src/app -L 1 src/app ├── admin/ ├── app-routing.module.ts ├── app.component.ts ├── app.module.ts ├── core/ ├── public/ └── shared/ CoreModule provides all the services and the Redux store SharedModule provides all the reusable components, directives or pipes PublicModule provides the components and routing of the public section of the app AdminModule provides the components and routing of the private section of the app AppModule root module (Show modules in the IDE)
  • 17. How to Enable Lazy Loading (2/4) Step 2: Create a routing module for lazy loaded module const routes: Routes = [{ path: '', component: AdminComponent, children: [ { path: '', redirectTo: 'list', pathMatch: 'full' }, { path: 'list', component: WorkshopListComponent }, { path: 'new', component: WorkshopEditorComponent }, { path: 'edit/:id', component: WorkshopEditorComponent }, ] }]; @NgModule({ imports: [ RouterModule.forChild(routes) ], exports: [ RouterModule ], }) export class AdminRoutingModule {} Always use the method forChild when importing the RouterModule Avoids duplication of services in the child injector
  • 18. How to Enable Lazy Loading (3/4) Step 3: Define a child <router-outlet> to render child routes @Component({ selector: 'rio-admin', template: ` <nav> <a routerLink="./list">List Workshops</a> <a routerLink="./new">Create Workshop</a> </nav> <router-outlet></router-outlet> `, }) export class AdminComponent {}
  • 19. How to Enable Lazy Loading (4/4) Step 4: Use the property loadChildren to lazy load the module export const routes: Routes = [{ path: 'admin', loadChildren: 'app/admin/admin.module#AdminModule', canActivate: [ AuthGuardService ], }]; @NgModule({ imports: [ RouterModule.forRoot(routes) ], exports: [ RouterModule ], }) export class AppRoutingModule {} Only in the root module use the forRoot method of RouterModule Never import a lazy loaded in this file, use a string as reference The path of loadChildren is not relative to the file, but to the index.html file (Show routes in the IDE and URL structure of the app)
  • 21. Enable Preloading Define the property preloadingStrategy in the root module routing import { PreloadAllModules } from '@angular/router'; export const routes: Routes = [ ... ]; @NgModule({ imports: [ RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules }) ], exports: [ RouterModule ], }) export class AppRoutingModule {}
  • 23. What's Change Detection (CD)? It's a mechanism to keep our "models" in sync with our "views" Change detection is fired when... The user interacts with the app (click, submit, etc.) An async event is completed (setTimeout, promise, observable) When CD is fired, Angular will check every component starting from the top once.
  • 24. Change Detection Strategy: OnPush Angular offers 2 strategies: Default: Check the entire component when CD is fired OnPush: Check only relevant subtrees when CD is fired OnPush Requirements: Component inputs ( @Input ) need to be immutable objects @Component({ selector: 'rio-workshop', templateUrl: './workshop.component.html', changeDetection: ChangeDetectionStrategy.OnPush }) export class WorkshopComponent { @Input() workshop: Workshop; @Input() isSummary = false; } View Example
  • 28. Summary What to do? Apply the OnPush change detection on every component* Never mutate an object or array, always create a a new reference ( )blog // Don't let addPerson = (person: Person): void => { people.push(person); }; // Do let addPerson = (people: Person[], person: Person): Person[] => { return [ ...people, person ]; }; Benefits: Fewer checks of your components during Change Detection Improved overall app performance
  • 30. What's Memory Leak? The increase of memory usage over time
  • 31. What Causes Memory Leaks in Angular? Main Source => Subscriptions to observables never closed @Injectable() export class WorkshopService { getAll(): Observable<Workshop[]> { ... } } @Component({ selector: 'rio-workshop-list', template: ` <div *ngFor="let workshop of workshops"> {{ workshop.title }} </div>` }) export class WorkshopListComponent implements OnInit { ... ngOnInit() { this.service.getAll().subscribe(workshops => this.workshops = workshops); } }
  • 32. Manually Closing Connections Before the element is destroyed, close the connection @Component({ selector: 'rio-workshop-list', template: ` <div *ngFor="let workshop of workshops"> {{ workshop.title }} </div>` }) export class WorkshopListComponent implements OnInit, OnDestroy { ... ngOnInit() { this.subscription = this.service.getAll() .subscribe(workshops => this.workshops = workshops); } ngOnDestroy() { this.subscription.unsubscribe(); } }
  • 33. The async Pipe It closes the connection automatically when the component is destroyed @Component({ selector: 'rio-workshop-list', template: ` <div *ngFor="let workshop of workshops$ | async"> {{ workshop.title }} </div>` }) export class WorkshopListComponent implements OnInit { ngOnInit() { this.workshops$ = this.service.getAll(); } } This is the recommended way of dealing with Observables in your template!
  • 34. The Http Service Every method of the http services ( get , post , etc.) returns an observable Those observables emit only one value and the connection is closed automatically They won't cause memory leak issues @Component({ selector: 'rio-workshop-list', template: ` <div *ngFor="let workshop of workshops"> {{ workshop.title }} </div>` }) export class WorkshopListComponent implements OnInit { ... ngOnInit() { this.http.get('some-url') .map(data => data.json()) .subscribe(workshops => this.workshops = workshops); } }
  • 35. Emit a Limited Number of Values RxJs provides operators to close the connection automatically Examples: first() and take(n) This won't cause memory leak issues even if getAll emits multiple values @Component({ selector: 'rio-workshop-list', template: ` <div *ngFor="let workshop of workshops"> {{ workshop.title }} </div>` }) export class WorkshopListComponent implements OnInit { ngOnInit() { this.service.getAll().first() .subscribe(workshops => this.workshops = workshops); } }
  • 37. Angular Universal Provides the ability to pre-render your application on the server Much faster time to first paint Enables better SEO Enables content preview on social networks Fallback support for older browsers Use the as the base of your applicationuniversal-starter
  • 38. What's Included Suite of polyfills for the server Server rendering layer Preboot - replays your user's interactions after Angular has bootstrapped State Rehydration - Don't lose your place when the application loads
  • 39. Boot Time Comparison (Client vs Server) Both environments include previous AoT and Lazy Loading enhancements Event Time (Client) Time (Server) DOM Content Loaded 3.11 s 411 ms Load 3.25 s 2.88 s FMP 3.16 s ~440 ms *Times are on mobile over 3G
  • 40. Universal Caveats Cannot directly access the DOM constructor(element: ElementRef, renderer: Renderer) { renderer.setElementStyle(element.nativeElement, ‘font-size’, ‘x-large’); } Current solutions only cover Express and ASP.NET servers Project will be migrated into the core Angular repo for v4
  • 42. Performance Changes Event JiT AoT Lazy Loading SSR DOM Content Loaded 5.44 s 3.25 s 3.11 s 411 ms Load 5.46 s 3.27 s 3.25 s 2.88 s FMP 5.46 s 3.30 s 3.16 s ~440 ms % Improvement (FMP) 39.6% 4.3% 86.1% *Times are on mobile over 3G