Advanced Angular: Praktische Real-World-Projekterfahrungen

Advanced Angular: Praktische Real-World-Projekterfahrungen

Die Grundlagen von Angular sind vermittelt – nun geht es an den täglichen Einsatz in Ihren Projekten! Christian Liebel zeigt Ihnen auf Basis seiner Erfahrungen aus etlichen Kundenprojekten, wie Sie weiteres Optimierungspotenzial für Ihre Anwendungen entfalten können: Lazy Loading, Change-Detection-Strategien, NgZone, Immutables, Observables, Server-Side Rendering, und der Production-Build der Angular CLI sind nur einige Maßnahmen, um aus Ihrer Angular-Anwendung noch einmal deutlich mehr Performance herauszuholen, als Sie es zur Entwicklungszeit bereits gewohnt sind.

12c88a3a10478fa18d0363b3ba3d9df1?s=128

Christian Liebel

March 20, 2018
Tweet

Transcript

  1. Christian Liebel @christianliebel Consultant Advanced Angular: Praktische Real-World-Projekterfahrungen Angular Days

    2018
  2. Christian Liebel Thinktecture AG Microsoft MVP Visual Studio and Development

    Technologies Twitter: @christianliebel E-Mail: christian.liebel@thinktecture.com https://thinktecture.com https://christianliebel.com Gestatten? Praktische Real-World-Projekterfahrungen Advanced Angular
  3. Was Sie nicht erwartet Einführung/Grundlagen von Angular, Single-Page Web Applications

    oder JavaScript Lösungen, die zu 100% auf Ihren Anwendungsfall übertragbar sind „Echtes“ Hands-On Was Sie erwartet Fünf praktische Beispiele von der Projektfront Problemanalysen, sofern anwendbar Produktionsreife Lösungsansätze Praktische Real-World-Projekterfahrungen Advanced Angular
  4. 09:00–10:30 Part I 10:30–11:00 Coffee break 11:00–12:30 Part II Timetable

    Praktische Real-World-Projekterfahrungen Advanced Angular
  5. Angular 5/6/… • Time-based release schedule (6 months) • March/April:

    even version • September/October: odd version • Semantic versioning: MAJOR.MINOR.PATCH • MAJOR: (Possible) breaking change • MINOR: New feature, backwards-compatible • PATCH: Bug fix, backwards-compatible • Deprecation Policy • Compatibility to previous major version (1 year) • Long-Term Supported Version (critical fixes/security patches only) • 4.x until Oct 2017–18 (1.5 years) Intro Praktische Real-World-Projekterfahrungen Advanced Angular
  6. Four real-world scenarios Five exercises Six topics Hands-on! liebel.io/ngd18adv Intro

    EX #0 Praktische Real-World-Projekterfahrungen Advanced Angular
  7. git pull git reset --hard Advanced Angular Praktische Real-World-Projekterfahrungen Helpful

    Git Commands
  8. Cross-Platform Support • Single-Page Applications • Handling Platform Differences Build

    Process • Angular CLI • Custom Build Angular Architecture • Observables • Lazy Loading Bundling • Ahead of Time Compilation • Tree Shaking Server-Side Rendering • Angular Universal • Preboot.js Performance • Change Detection Strategies • Immutables • Zone.js Praktische Real-World-Projekterfahrungen Advanced Angular
  9. The Problem Diversity of devices and platforms Resources (personnel, time,

    money) are limited “Write once, run anywhere” Error rate grows with code base size Cross-Platform Support Praktische Real-World-Projekterfahrungen Advanced Angular
  10. HTML5, CSS3 and JavaScript • Desktop: Windows, macOS, Linux, …

    • Mobile: iOS, Android, Windows 10 Mobile, … • Browser: Chrome, Firefox, Edge, Safari, … • Others: Nintendo DS, Refrigerator, … Cross-Platform Support “Real Cross Platform” Praktische Real-World-Projekterfahrungen Advanced Angular
  11. Single-Page Web Apps Single-Page Web Applications (SPA) are the preferred

    model for implementing large-scale apps “Fat clients”/Rich Internet Applications Angular is an SPA framework cross-platform support out of the box Cross-Platform Support Praktische Real-World-Projekterfahrungen Advanced Angular
  12. Developer Responsibilities Responsive Design • Bootstrap, Flexbox, … Client App

    Architecture • Local data storage • Distributed system architecture Cross-Platform Support Praktische Real-World-Projekterfahrungen Advanced Angular
  13. Tools Cordova (PhoneGap) for mobile platforms Electron for desktop platforms

    Cross-Platform-Support Praktische Real-World-Projekterfahrungen Advanced Angular
  14. Cordova & Electron Cross-Platform-Support JS HTML CSS .ipa .exe .app

    ELF .apk .appx Single-Page Web Application Cordova Electron Praktische Real-World-Projekterfahrungen Advanced Angular
  15. 1 Code Base, X Platforms Cross-Platform Support Praktische Real-World-Projekterfahrungen Advanced

    Angular
  16. 1 Code Base, X Platforms Cross-Platform Support Praktische Real-World-Projekterfahrungen Advanced

    Angular
  17. Handling Platform Differences Different APIs depending on the environment, e.g.

    camera access Browser/Electron: navigator.mediaDevices.getUserMedia() Cordova: navigator.camera.getPicture() Cross-Platform Support Praktische Real-World-Projekterfahrungen Advanced Angular
  18. How To Base Camera Service Mobile Camera Service Desktop Camera

    Service { provide: CameraService, useFactory: CameraServiceFactory } export function CameraServiceFactory() { // return ???; } Cross-Platform Support EX #1 Praktische Real-World-Projekterfahrungen Advanced Angular
  19. Recap Can be easily handled by Angular’s DI Provide base

    type and concrete implementations (e.g. desktop/mobile) Cross-Platform Support Praktische Real-World-Projekterfahrungen Advanced Angular
  20. Recap Masquerading platform differences by dependency injection and polymorphism Prevents

    endless switch blocks, #ifdef compiler flags, … constructor(private _camera: CameraService) { } // this._camera.getPicture(); Cross-Platform Support Praktische Real-World-Projekterfahrungen Advanced Angular
  21. Mobile Website Only In Non-App Scenarios • Angular Universal •

    @angular/service-worker Cross-Platform Support Praktische Real-World-Projekterfahrungen Advanced Angular
  22. @angular/service-worker Service Workers • Caching • Offline Availability • Push

    Notifications Focused on Progressive Web Apps Service worker generation supported by CLI ng new project --service-worker Cross-Platform Support Praktische Real-World-Projekterfahrungen Advanced Angular
  23. App Stores Progressive Web Apps Praktische Real-World-Projekterfahrungen Advanced Angular

  24. Apps tomorrow… • Idea: No App Store required • Web

    App = App App • Feature Parity: Native Experience leveraging Push notifications, Offline capability, … • Powered by Google, available on Android today • Backwards compatible (Progressive Enhancement) • PWA is not a technology, but a list of features/requirements Progressive Web Apps (PWA) Praktische Real-World-Projekterfahrungen Advanced Angular
  25. Safe Progressive Responsive Connectivity Independent App-like Fresh Discoverable Re- engageable

    Installable Linkable Progressive Web Apps are… https://developers.google.com/web/fundamentals/getting-started/codelabs/your-first-pwapp/ Praktische Real-World-Projekterfahrungen Advanced Angular
  26. Progressive Web Apps HTML5, JavaScript, CSS3 Service Worker API Fetch

    API Web Notifications Web Workers Push API Web App Manifest HTTPS Progressive Web Apps Praktische Real-World-Projekterfahrungen Advanced Angular
  27. Cross-Platform Support • Single-Page Applications • Handling Platform Differences Build

    Process • Angular CLI • Custom Build Angular Architecture • Observables • Lazy Loading Bundling • Ahead of Time Compilation • Tree Shaking Server-Side Rendering • Angular Universal • Preboot.js Performance • Change Detection Strategies • Immutables • Zone.js Praktische Real-World-Projekterfahrungen Advanced Angular
  28. The Problem Web application development is getting more complex Usage

    of source-to-source compilers like TypeScript, Sass, Less, … Fast and easy development and production We need a build process! Build Process Praktische Real-World-Projekterfahrungen Advanced Angular
  29. Angular CLI > npm install -g @angular/cli > ng new

    my-app Build Process Praktische Real-World-Projekterfahrungen Advanced Angular
  30. Angular CLI Usage Bootstrapping • ng new project Scaffolding •

    ng generate component foo Build process • ng build Development server • ng serve Build Process Praktische Real-World-Projekterfahrungen Advanced Angular
  31. Angular CLI Advantages Extremely easy and fast setup No configuration

    E2E and unit test support A good starting point for • learning Angular basics • seeing quick results (generalized use cases, private projects) Build Process Praktische Real-World-Projekterfahrungen Advanced Angular
  32. Angular CLI Drawbacks Opinionated directory structure/naming “One size fits all”

    build process Hardly extensible/configurable (as of 1.4.4) Build Process Praktische Real-World-Projekterfahrungen Advanced Angular
  33. Angular CLI Eject ng eject since 1.0.0-beta.32 “Ejects” Webpack configuration

    and build scripts to project scope ng build => npm run build Problem: build scripts are getting stale Build Process Praktische Real-World-Projekterfahrungen Advanced Angular
  34. More flexibility (e.g. 2+ repositories) e.g. based on Gulp/FuseBox/Webpack/… (or

    ejected Angular CLI build) Tailored to the customer’s needs Setting up a custom-tailored build process can take a considerable amount of time New Thinktecture customer projects are all on Angular CLI Build Process Angular CLI vs. Custom Build Praktische Real-World-Projekterfahrungen Advanced Angular
  35. gulp.task('prod:bundle', done => { return rollup({ entry: './build/aot/src/app/main.aot.js', format: 'iife',

    plugins: [ nodeResolve({ jsnext: true, module: true }), commonjs(), uglify() ] }) .pipe(source('app.js')) .pipe(gulp.dest(config.prod.target)) }); Custom Gulp Build Step Sample Build Process Praktische Real-World-Projekterfahrungen Advanced Angular
  36. Cross-Platform Support • Single-Page Applications • Handling Platform Differences Build

    Process • Angular CLI • Custom Build Angular Architecture • Observables • Lazy Loading Bundling • Ahead of Time Compilation • Tree Shaking Server-Side Rendering • Angular Universal • Preboot.js Performance • Change Detection Strategies • Immutables • Zone.js Praktische Real-World-Projekterfahrungen Advanced Angular
  37. Observables Asynchronous, event-based applications Operate with values that change continuously

    over time Angular has Observables support built right in Using RxJS (JavaScript edition of Reactive Extensions) High-Level Flow Composition (map, switchMap) Angular Architecture Praktische Real-World-Projekterfahrungen Advanced Angular
  38. RxJS Operators Angular Architecture http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-switchMap Praktische Real-World-Projekterfahrungen Advanced Angular

  39. Observables vs. Promises Observables • Can return multiple values over

    time • Can manage multiple listeners • Can be cancelled • Intended for composing flow and sequences of asynchronous data Should we always use Observables? Use the right tool for the right job. Promises (native ES 2015 feature) might be just enough! Angular Architecture Praktische Real-World-Projekterfahrungen Advanced Angular
  40. Observables Observables are everywhere around in Angular Example: Routing You

    can subscribe to route parameter changes and react to them without re-instantiating the component (performance) Example: HTTP Angular’s HttpClient returns Observables by default This can be combined using RxJS’s operators. Angular Architecture Praktische Real-World-Projekterfahrungen Advanced Angular
  41. How To Observables Subscribe to route parameter changes Send a

    request to the StarWars API (https://swapi.co) Combine both asynchronous operations: If the user navigates away or changes the route before the request returns, cancel it. Praktische Real-World-Projekterfahrungen Advanced Angular
  42. How To 1. Inject ActivatedRoute into your component 2. Bind

    to params 3. Extract “ID” from the params object (data over time) 4. Start an HTTP request and cancel the in-flight request (if any); use switchMap here. Angular Architecture Praktische Real-World-Projekterfahrungen Advanced Angular EX #2
  43. Pipeable Operators import {Observable} from 'rxjs'; import 'rxjs/add/observable/of'; import 'rxjs/add/operator/map';

    Observable.of({ list: [1, 2, 3] }) .map(obj => obj.list) .subscribe(list => alert(list)); Angular Architecture Praktische Real-World-Projekterfahrungen Advanced Angular Problem: Side-effect imports Observable method/operator import is valid for the entire code base Deleting an import statement in a file may break different (maybe even unknown) ones
  44. Pipeable Operators import {Observable} from 'rxjs'; import 'rxjs/add/observable/of'; import 'rxjs/add/operator/map';

    Observable.of({ list: [1, 2, 3] }) .map(obj => obj.list) .subscribe(list => alert(list)); Angular Architecture Praktische Real-World-Projekterfahrungen Advanced Angular import {of} from 'rxjs/observable/of'; import {map} from 'rxjs/operators'; of({ list: [1, 2, 3] }).pipe( map(obj => obj.list) ).subscribe(list => alert(list));
  45. Observables Make sure to unsubscribe from an observable (Memory Leaks)

    • By unsubscribing from the observable (user; long-lived observables) const sub: Subscription = getObservable().subscribe(x => console.log(x)); sub.unsubscribe(); • By completing the observable (provider; short-lived observables) • By using the async pipe Angular Architecture Praktische Real-World-Projekterfahrungen Advanced Angular
  46. Recap Observables Multiple values, multiple listeners, cancellable Observables are the

    preferred way for handling asynchronous operations in Angular Can be easily combined using the operators of RxJS Use pipeable operators! There are cases where Promises might just be enough Using the async pipe is the preferred way Less code, no manual unsubscribe, triggers change detection Praktische Real-World-Projekterfahrungen Advanced Angular
  47. Lazy Loading Angular router supports lazy loading components transparently Lazy

    loaded components are not delivered to/loaded by the client on boot, but on purpose Loaded on usage or in the background after the boot (preloading) Custom preloading strategies Reduces load & perceived loading time Angular Architecture Praktische Real-World-Projekterfahrungen Advanced Angular
  48. Lazy Loading const ROUTES: Routes = [{ path: 'admin', loadChildren:

    'app/admin/admin.module#AdminModule' }]; Angular Architecture Praktische Real-World-Projekterfahrungen Advanced Angular
  49. Lazy Loading Lazy Loading is module-based Module is resolved by

    a module reference (e.g. SystemJS “URL”) Routing is delegated to the module called Angular Architecture EX #3 Praktische Real-World-Projekterfahrungen Advanced Angular
  50. Cross-Platform Support • Single-Page Applications • Handling Platform Differences Build

    Process • Angular CLI • Custom Build Angular Architecture • Observables • Lazy Loading Bundling • Ahead of Time Compilation • Tree Shaking Server-Side Rendering • Angular Universal • Preboot.js Performance • Change Detection Strategies • Immutables • Zone.js Praktische Real-World-Projekterfahrungen Advanced Angular
  51. The Problem Angular’s development directory structure is hard to •

    deploy • serve • cache • … Lots of files, lots of requests Angular and its dependencies are large in size, apps use only a fragment Bundling Praktische Real-World-Projekterfahrungen Advanced Angular
  52. The Problem Just-in-Time compilation (JiT) • Slow, client-side rendering •

    Compiler is 1.2 MB large in size • Template errors detected at runtime only • Potentially dangerous (injection attacks) Bundling Praktische Real-World-Projekterfahrungen Advanced Angular
  53. The Problem Goal: Angular app • with all components pre-compiled

    • combined in a single (or few) file(s) • without redundant/unused code • uglified, compressed Bundling Praktische Real-World-Projekterfahrungen Advanced Angular
  54. Measures Ahead-of-Time (AoT) compilation • Pre-compiling all modules and components

    (offline) Bundling • Tree Shaking • Uglify • Compress • … Bundling Praktische Real-World-Projekterfahrungen Advanced Angular
  55. Status Quo Angular CLI • uses Just in Time (JiT)

    compilation per default • provides AoT & production build out of the box AoT requires some additional steps Pre-compiling the application using the (offline) Angular compiler ngc A different Angular runtime platform has to be used Bundling Praktische Real-World-Projekterfahrungen Advanced Angular
  56. Platforms & Renderers Angular is platform-independent, i.e. Angular-based apps can

    run outside of the browser • AngularJS: hides information in DOM Angular provides support for custom renderers Bundling Praktische Real-World-Projekterfahrungen Advanced Angular
  57. Platforms platformBrowserDynamic • JiT platformBrowser • AoT • only pre-rendered

    component factories exist • ngc is executed before deployment Bundling Praktische Real-World-Projekterfahrungen Advanced Angular
  58. Platforms platformServer • Server-Side Rendering (Angular Universal) platformNativeScriptDynamic • Building

    native apps with Angular platformWorkerApp • Render in Web Worker (background thread) Bundling Praktische Real-World-Projekterfahrungen Advanced Angular
  59. Angular Compilation Bundling https://www.youtube.com/watch?v=kW9cJsvcsGo Component @Component({ … }) class UserComponent

    { user = { name: 'Chris' }; } Template <div>hello {{ user.name }}</div> View Class var v = this.comp.user.name; Praktische Real-World-Projekterfahrungen Advanced Angular
  60. <h1>{{ title }}</h1> Bundling Praktische Real-World-Projekterfahrungen Advanced Angular

  61. JiT Compilation Bundling Component @Component({ … }) class UserComponent {

    user = { name: 'Chris' }; } Template <div>hello {{ user.name }}</div> Server Client Component @Component({ … }) class UserComponent { user = { name: 'Chris' }; } Template <div>hello {{ user.name }}</div> View Class var v = this.comp.user.name; Praktische Real-World-Projekterfahrungen Advanced Angular
  62. AoT Compilation Bundling Component @Component({ … }) class UserComponent {

    user = { name: 'Chris' }; } Template <div>hello {{ user.name }}</div> Server Client Component @Component({ … }) class UserComponent { user = { name: 'Chris' }; } View Class var v = this.comp.user.name; Template <div>hello {{ user.name }}</div> View Class var v = this.comp.user.name; Praktische Real-World-Projekterfahrungen Advanced Angular
  63. Tree Shaking “A Tree Shaker walks the dependency graph, top

    to bottom, and shakes out unused code like dead needles in a Christmas tree.” Bundling Praktische Real-World-Projekterfahrungen Advanced Angular
  64. !function(){ var obj = { foo: function () { //

    Hi there! }, bar: function () { this.baz(); }, baz: function () { // stub } }; obj.foo(); }(); Tree Shaking Principle Bundling Praktische Real-World-Projekterfahrungen Advanced Angular
  65. Build-Optimizer Contains Angular optimizations applicable to JavaScript code Folding static

    properties inside the class, scrubbing decorators, … Transformations help build tools to improve tree shaking Only in combination with AoT Enabled by default for AoT/production builds starting from Angular 5 Bundling Praktische Real-World-Projekterfahrungen Advanced Angular
  66. Build-Optimizer Bundling Praktische Real-World-Projekterfahrungen Advanced Angular EX #4

  67. Recap ng new demo-app ng build //no TS, JiT, no

    BO ng build --aot //no TS, AoT, no BO ng build --prod --build-optimizer=false // TS, AoT, no BO ng build --prod // TS, AoT, BO Bundling Praktische Real-World-Projekterfahrungen Advanced Angular
  68. A Simple Demo App Dev build: 2.7 MB (without source

    maps) AoT build: 1.4 MB (without source maps) AoT+TreeShake: 301K AoT+TreeShake+BuildOptimizer: 224K (108K gzipped) Bundling Praktische Real-World-Projekterfahrungen Advanced Angular
  69. A Simple Demo App JiT build: ~4500 ms AoT build:

    ~3800 ms Optimized build: ~3800ms Mid 2015 MacBook Pro, served locally a few test runs, results may & will vary Bundling Praktische Real-World-Projekterfahrungen Advanced Angular
  70. AoT Drawbacks Dynamic template compilation via ComponentFactoryResolver is discouraged in

    combination with AoT COMPILER_PROVIDERS are unavailable • https://github.com/angular/angular/issues/11780 Bundling Praktische Real-World-Projekterfahrungen Advanced Angular
  71. Cross-Platform Support • Single-Page Applications • Handling Platform Differences Build

    Process • Angular CLI • Custom Build Angular Architecture • Observables • Lazy Loading Bundling • Ahead of Time Compilation • Tree Shaking Server-Side Rendering • Angular Universal • Preboot.js Performance • Change Detection Strategies • Immutables • Zone.js Praktische Real-World-Projekterfahrungen Advanced Angular
  72. Angular Universal Provided by the Angular team Open Source •

    https://github.com/angular/universal CLI integration now possible • https://github.com/angular/angular-cli/wiki/stories-universal- rendering Server-Side Rendering Praktische Real-World-Projekterfahrungen Advanced Angular
  73. Isomorphic vs. Universal Isomorphic (2011) Ability of JavaScript apps to

    run on both the server and the client Isomorphic JavaScript (2013) Future of web apps, same source is used to render on server/client Universal JavaScript (2015) JavaScript that is able to run in any environment Server-Side Rendering Praktische Real-World-Projekterfahrungen Advanced Angular
  74. Angular App Application Layer Rendering Layer Web Worker Server Browser

    NativeScript … Platform Server-Side Rendering Praktische Real-World-Projekterfahrungen Advanced Angular
  75. Principle Pre-render the website using the same sources that are

    served Once Angular kicks in, the view is replaced with the client-rendered one Supports Node.js, ASP.NET Core, … Support planned for Java, PHP, … JiT and AoT support (AoT strictly recommended for production) Server-Side Rendering Praktische Real-World-Projekterfahrungen Advanced Angular
  76. Principle Server-Side Rendering Component @Component({ … }) class UserComponent {

    user = { name: 'Chris' }; } Template <div>hello {{ user.name }}</div> Server Client Component @Component({ … }) class UserComponent { user = { name: 'Chris' }; } View Class var v = this.comp.user.name; Template <div>hello {{ user.name }}</div> View Class var v = this.comp.user.name; index.html <!DOCTYPE html><head>… Praktische Real-World-Projekterfahrungen Advanced Angular
  77. Purpose Search Engine Optimization Preview Links (Social Media) Graceful Degradation

    Reduce Perceived Loading Time Server-Side Rendering Praktische Real-World-Projekterfahrungen Advanced Angular
  78. Server Rendering Asset Downloads Client Init Client Data Paint The

    Web App Gap Server-Side Rendering Praktische Real-World-Projekterfahrungen Advanced Angular
  79. Preboot.js Filling the Web App Gap Records interactions of the

    user on the server-rendered part Replays the interaction once Angular kicks in on the client side Server-Side Rendering Praktische Real-World-Projekterfahrungen Advanced Angular
  80. Server Rendering Asset Downloads Client Init Client Data Paint Preboot.js

    & The Web App Gap Advanced Angular Praktische Real-World-Projekterfahrungen Server-Side Rendering Record Replay
  81. Cross-Platform Support • Single-Page Applications • Handling Platform Differences Build

    Process • Angular CLI • Custom Build Angular Architecture • Observables • Lazy Loading Bundling • Ahead of Time Compilation • Tree Shaking Server-Side Rendering • Angular Universal • Preboot.js Performance • Change Detection Strategies • Immutables • Zone.js Praktische Real-World-Projekterfahrungen Advanced Angular
  82. Single-Page Web App Performance Data Flow Component Communication Change Detection

    Performance Praktische Real-World-Projekterfahrungen Advanced Angular
  83. Angular Performance Uni-directional data flow (exclusively) Prevents change detection cycles

    • AngularJS: 10 $digest() iterations reached “Virtual” two-way binding in Angular by combining property/event bindings • Banana in a box/compiler magic: [(ngModel)] Performance Praktische Real-World-Projekterfahrungen Advanced Angular
  84. Change Detection Strategies <my-component [foo]="bar"> </my-component> @Component({ selector: 'my-component', template:

    '{{ foo }}', changeDetection: ChangeDetectionStrategy.OnPush }) export class MyComponent { @Input() public foo: string; } Components can restrict change detection to changes of @Input parameters (OnPush) Immutables are required, otherwise model and view can get out of sync Performance Praktische Real-World-Projekterfahrungen Advanced Angular
  85. Immutable.js to the rescue Immutable.js is a library that does

    not update data in place, but yields updated data instead https://facebook.github.io/immutable-js/ const map1 = Immutable.Map({ a: 1, b: 2, c: 3 }); const map2 = map1.set('b', 50); map1.get('b'); // 2 map2.get('b'); // 50 map2.toObject(); // { a: 1, b: 50, c: 3 } Performance Praktische Real-World-Projekterfahrungen Advanced Angular
  86. Change Detection Strategies ChangeDetectionStrategy.Default Magically checks for changes and updates

    bindings accordingly But how? Performance Praktische Real-World-Projekterfahrungen Advanced Angular
  87. A look at Angular’s dependencies "dependencies": { "@angular/common": "^4.2.4", "core-js":

    "^2.4.1", "rxjs": "^5.4.2", "zone.js": "^0.8.14" }, Performance Praktische Real-World-Projekterfahrungen Advanced Angular
  88. Zone.js Provided by the Angular team • https://github.com/angular/zone.js Provides an

    execution context for asynchronous JavaScript A meta-monkey patch Performance Praktische Real-World-Projekterfahrungen Advanced Angular
  89. Execution Context function main() { // const start = performance.now();

    a(); setTimeout(b, 0); c(); // const stop = performance.now(); // const ms = stop - start; } Performance Praktische Real-World-Projekterfahrungen Advanced Angular
  90. Zone.js Oversimplified Zone.run(main); onZoneEnter(); function main() { a(); setTimeout(b, 0);

    c(); } onZoneLeave(); Performance const orig = window.setTimeout; window.setTimeout = (c, t) => { orig(() => { onZoneEnter(); c(); onZoneLeave(); }, t); }; Praktische Real-World-Projekterfahrungen Advanced Angular
  91. Benefits Debugging: Pending asynchronous tasks are known Profiling: Measuring performance

    (Google Web Tracing Framework) Mocking/Testing: Hooks beforeTask, … Performance Praktische Real-World-Projekterfahrungen Advanced Angular
  92. A Meta-Monkey Patch Performance setTimeout setInterval geolocation.getCurrentPosition XMLHttpRequest PromiseRejectionEvent requestAnimationFrame

    click focus mousemove addEventListener Praktische Real-World-Projekterfahrungen Advanced Angular
  93. Zone.js Angular’s change detection is based on Zone.js • AngularJS

    digest cycle: $timeout, $apply() Angular is running inside an own zone, referred to as the NgZone Performance Praktische Real-World-Projekterfahrungen Advanced Angular
  94. NgZone Performance current (global) zone NgZone Angular boot Praktische Real-World-Projekterfahrungen

    Advanced Angular
  95. Boxes, draggable around the screen Component requires “default” change detection

    (i.e. it can’t rely on input changes) Dragging performance drops drastically with an increasing number of boxes The Problem Performance Praktische Real-World-Projekterfahrungen Advanced Angular
  96. Performance Status Quo Praktische Real-World-Projekterfahrungen Advanced Angular

  97. NgZone Performance current (global) zone NgZone mousemove Detect changes mousemove

    Detect changes mousemove Detect changes mousemove Detect changes Praktische Real-World-Projekterfahrungen Advanced Angular
  98. Running Outside Angular constructor (ngZone: NgZone) { ngZone.runOutsideAngular(() => {

    // runs outside Angular zone ngZone.run(() => { // runs inside Angular zone }); }); } Performance Praktische Real-World-Projekterfahrungen Advanced Angular
  99. The Fix Run performance-critical code outside Angular Setting the box

    location directly via Renderer2 & ElementRef.nativeElement Performance Praktische Real-World-Projekterfahrungen Advanced Angular
  100. The Fix Use of Renderer2 is crucial to stay platform

    independent elementRef.nativeElement.style.left = "3px"; renderer2.setStyle(elementRef.nativeElement, "left", "3px"); Performance EX #5 Praktische Real-World-Projekterfahrungen Advanced Angular
  101. NgZone Performance current (global) zone NgZone mousemove mousemove mousemove mousemove

    Praktische Real-World-Projekterfahrungen Advanced Angular
  102. The Fix Performance Praktische Real-World-Projekterfahrungen Advanced Angular

  103. The Fix In particular, this has also helped fixing Protractor

    timeouts when long- running asynchronous tasks are launched on application startup • https://christianliebel.com/2016/11/angular-2-protractor-timeout- heres-fix/ Performance Praktische Real-World-Projekterfahrungen Advanced Angular
  104. Cross-Platform Support • Single-Page Applications • Handling Platform Differences Build

    Process • Angular CLI • Custom Build Angular Architecture • Observables • Lazy Loading Bundling • Ahead of Time Compilation • Tree Shaking Server-Side Rendering • Angular Universal • Preboot.js Performance • Change Detection Strategies • Immutables • Zone.js Praktische Real-World-Projekterfahrungen Advanced Angular
  105. Any questions? Praktische Real-World-Projekterfahrungen Advanced Angular

  106. Thank you for your kind attention! Christian Liebel @christianliebel christian.liebel@thinktecture.com