SlideShare uma empresa Scribd logo
1 de 39
Baixar para ler offline
Small computers, big performance:
Optimize your Angular
Speakers
David Barreto
Solutions Architect @ Rangle.io
Blog: david-barreto.com
Andrew Smith
Solutions Architect @ Rangle.io
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 Angular Universal
All the numbers shown are based on:
Low end device (5x CPU slowdown)
Good 3G connection (Latency: 40ms, DL: 1.5 Mbps, UL: 750 Kbps)
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
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
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
Thank You
Slides: https://github.com/rangle/angular-performance-meetup

Mais conteúdo relacionado

Mais procurados

Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3Elixir Club
 
2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & Webpack2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & WebpackCodifly
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Libraryasync_io
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaFrank Lyaruu
 
Legacy Code Kata v3.0
Legacy Code Kata v3.0Legacy Code Kata v3.0
Legacy Code Kata v3.0William Munn
 
Reactive programming with RxJava
Reactive programming with RxJavaReactive programming with RxJava
Reactive programming with RxJavaJobaer Chowdhury
 
Jquery- One slide completing all JQuery
Jquery- One slide completing all JQueryJquery- One slide completing all JQuery
Jquery- One slide completing all JQueryKnoldus Inc.
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in JavaRuben Inoto Soto
 
Legacy Dependency Kata v2.0
Legacy Dependency Kata v2.0Legacy Dependency Kata v2.0
Legacy Dependency Kata v2.0William Munn
 
HKG15-204: OpenStack: 3rd party testing and performance benchmarking
HKG15-204: OpenStack: 3rd party testing and performance benchmarkingHKG15-204: OpenStack: 3rd party testing and performance benchmarking
HKG15-204: OpenStack: 3rd party testing and performance benchmarkingLinaro
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future TaskSomenath Mukhopadhyay
 
Sword fighting with Dagger GDG-NYC Jan 2016
 Sword fighting with Dagger GDG-NYC Jan 2016 Sword fighting with Dagger GDG-NYC Jan 2016
Sword fighting with Dagger GDG-NYC Jan 2016Mike Nakhimovich
 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSKnoldus Inc.
 
AngularJS Unit Test
AngularJS Unit TestAngularJS Unit Test
AngularJS Unit TestChiew Carol
 
Async JavaScript Unit Testing
Async JavaScript Unit TestingAsync JavaScript Unit Testing
Async JavaScript Unit TestingMihail Gaberov
 

Mais procurados (20)

Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3
 
2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & Webpack2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & Webpack
 
Alteryx SDK
Alteryx SDKAlteryx SDK
Alteryx SDK
 
Ondemand scaling-aws
Ondemand scaling-awsOndemand scaling-aws
Ondemand scaling-aws
 
Performance tests with Gatling
Performance tests with GatlingPerformance tests with Gatling
Performance tests with Gatling
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJava
 
Legacy Code Kata v3.0
Legacy Code Kata v3.0Legacy Code Kata v3.0
Legacy Code Kata v3.0
 
Reactive programming with RxJava
Reactive programming with RxJavaReactive programming with RxJava
Reactive programming with RxJava
 
Jquery- One slide completing all JQuery
Jquery- One slide completing all JQueryJquery- One slide completing all JQuery
Jquery- One slide completing all JQuery
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
Legacy Dependency Kata v2.0
Legacy Dependency Kata v2.0Legacy Dependency Kata v2.0
Legacy Dependency Kata v2.0
 
HKG15-204: OpenStack: 3rd party testing and performance benchmarking
HKG15-204: OpenStack: 3rd party testing and performance benchmarkingHKG15-204: OpenStack: 3rd party testing and performance benchmarking
HKG15-204: OpenStack: 3rd party testing and performance benchmarking
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future Task
 
Sword fighting with Dagger GDG-NYC Jan 2016
 Sword fighting with Dagger GDG-NYC Jan 2016 Sword fighting with Dagger GDG-NYC Jan 2016
Sword fighting with Dagger GDG-NYC Jan 2016
 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJS
 
React lecture
React lectureReact lecture
React lecture
 
AngularJS Unit Test
AngularJS Unit TestAngularJS Unit Test
AngularJS Unit Test
 
Beyond Unit Testing
Beyond Unit TestingBeyond Unit Testing
Beyond Unit Testing
 
Async JavaScript Unit Testing
Async JavaScript Unit TestingAsync JavaScript Unit Testing
Async JavaScript Unit Testing
 

Semelhante a Angular Optimization Web Performance Meetup

Angular performance slides
Angular performance slidesAngular performance slides
Angular performance slidesDavid Barreto
 
High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2Niti Chotkaew
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax ApplicationsJulien Lecomte
 
Advanced iOS Build Mechanics, Sebastien Pouliot
Advanced iOS Build Mechanics, Sebastien PouliotAdvanced iOS Build Mechanics, Sebastien Pouliot
Advanced iOS Build Mechanics, Sebastien PouliotXamarin
 
Release with confidence
Release with confidenceRelease with confidence
Release with confidenceJohn Congdon
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsJeff Durta
 
Fundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfStephieJohn
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Roberto Franchini
 
Improving the Accumulo User Experience
 Improving the Accumulo User Experience Improving the Accumulo User Experience
Improving the Accumulo User ExperienceAccumulo Summit
 
react-slides.pdf gives information about react library
react-slides.pdf gives information about react libraryreact-slides.pdf gives information about react library
react-slides.pdf gives information about react libraryjanet736113
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]GDSC UofT Mississauga
 
Gitlab and Lingvokot
Gitlab and LingvokotGitlab and Lingvokot
Gitlab and LingvokotLingvokot
 
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years laterSymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years laterHaehnchen
 
How to Implement Micro Frontend Architecture using Angular Framework
How to Implement Micro Frontend Architecture using Angular FrameworkHow to Implement Micro Frontend Architecture using Angular Framework
How to Implement Micro Frontend Architecture using Angular FrameworkRapidValue
 
3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdfBOSC Tech Labs
 
Plugin-based software design with Ruby and RubyGems
Plugin-based software design with Ruby and RubyGemsPlugin-based software design with Ruby and RubyGems
Plugin-based software design with Ruby and RubyGemsSadayuki Furuhashi
 

Semelhante a Angular Optimization Web Performance Meetup (20)

Angular performance slides
Angular performance slidesAngular performance slides
Angular performance slides
 
High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
 
Advanced iOS Build Mechanics, Sebastien Pouliot
Advanced iOS Build Mechanics, Sebastien PouliotAdvanced iOS Build Mechanics, Sebastien Pouliot
Advanced iOS Build Mechanics, Sebastien Pouliot
 
Release with confidence
Release with confidenceRelease with confidence
Release with confidence
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
Fundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdf
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!
 
React js
React jsReact js
React js
 
Improving the Accumulo User Experience
 Improving the Accumulo User Experience Improving the Accumulo User Experience
Improving the Accumulo User Experience
 
react-slides.pptx
react-slides.pptxreact-slides.pptx
react-slides.pptx
 
react-slides.pdf
react-slides.pdfreact-slides.pdf
react-slides.pdf
 
react-slides.pdf gives information about react library
react-slides.pdf gives information about react libraryreact-slides.pdf gives information about react library
react-slides.pdf gives information about react library
 
React native
React nativeReact native
React native
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]
 
Gitlab and Lingvokot
Gitlab and LingvokotGitlab and Lingvokot
Gitlab and Lingvokot
 
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years laterSymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
 
How to Implement Micro Frontend Architecture using Angular Framework
How to Implement Micro Frontend Architecture using Angular FrameworkHow to Implement Micro Frontend Architecture using Angular Framework
How to Implement Micro Frontend Architecture using Angular Framework
 
3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf
 
Plugin-based software design with Ruby and RubyGems
Plugin-based software design with Ruby and RubyGemsPlugin-based software design with Ruby and RubyGems
Plugin-based software design with Ruby and RubyGems
 

Último

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 

Último (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 

Angular Optimization Web Performance Meetup

  • 1. Small computers, big performance: Optimize your Angular
  • 2. Speakers David Barreto Solutions Architect @ Rangle.io Blog: david-barreto.com Andrew Smith Solutions Architect @ Rangle.io
  • 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 Angular Universal All the numbers shown are based on: Low end device (5x CPU slowdown) Good 3G connection (Latency: 40ms, DL: 1.5 Mbps, UL: 750 Kbps)
  • 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
  • 8.
  • 9.
  • 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
  • 17. 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 {}
  • 19. 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.
  • 20. 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
  • 24. 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
  • 26. What's Memory Leak? The increase of memory usage over time
  • 27. 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); } }
  • 28. 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(); } }
  • 29. 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!
  • 30. 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); } }
  • 31. 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); } }
  • 33. 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
  • 34. 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
  • 35. 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
  • 36. 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
  • 38. 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