<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Francesco Cantarella on Medium]]></title>
        <description><![CDATA[Stories by Francesco Cantarella on Medium]]></description>
        <link>https://medium.com/@francesco-cantarella?source=rss-34a7c2467e79------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*xnSAz1bRtF6SXedb</url>
            <title>Stories by Francesco Cantarella on Medium</title>
            <link>https://medium.com/@francesco-cantarella?source=rss-34a7c2467e79------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 07:14:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@francesco-cantarella/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Angular optimisation: Load content below the fold]]></title>
            <link>https://medium.com/geekculture/angular-optimisation-load-content-below-the-fold-8ef87559c867?source=rss-34a7c2467e79------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ef87559c867</guid>
            <category><![CDATA[scroll]]></category>
            <category><![CDATA[angular-lazy-loading]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[above-the-fold]]></category>
            <category><![CDATA[below-the-fold]]></category>
            <dc:creator><![CDATA[Francesco Cantarella]]></dc:creator>
            <pubDate>Tue, 13 Jul 2021 16:32:44 GMT</pubDate>
            <atom:updated>2021-07-15T12:00:11.164Z</atom:updated>
            <content:encoded><![CDATA[<p>Loading a component on the page scroll</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*BeRrri7nOFnl0BYW0vwh_A.png" /></figure><p>To decrease the loading time of a page it is a good rule to load only the content above the fold, and load the content below the fold<br>only when the user scrolls the page.</p><p>To do this we will listen to the ‘scroll’ event on ‘window’ and we will mark an element on the page which, once visible, will trigger the ‘position reached’ event. Note that the ‘scroll’ event will be listen <strong>outside</strong> Angular for avoid a lot and unnecessary change detection cycles.<br>At this point we can load further content, such as a component of a module with the help of the “ng-dynamic-component” library and a service.</p><p>Let’s create a directive we call ‘tagReached’</p><pre><strong>tagReached.directive.ts</strong></pre><pre>import {<br>    AfterViewInit,<br>    ContentChild,<br>    Directive,<br>    ElementRef,<br>    EventEmitter,<br>    NgZone,<br>    OnDestroy,<br>    OnInit,<br>    Output<br>} from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br>import {Subscription} from &#39;rxjs&#39;;<br>import {debounceTime} from &#39;rxjs/operators&#39;;</pre><pre>import {CommonService} from &#39;../common.service&#39;;</pre><pre><a href="http://twitter.com/Directive">@Directive</a>({<br>    selector: &#39;[tagReached]&#39;<br>})<br>export class TagReachedDirective implements OnInit, AfterViewInit, OnDestroy {<br>$windowSize: Subscription;<br>documentHeight;<br>breakpointOffsetTop;<br>_scrollEventBind;<br> reachedEmitted = false;</pre><pre><a href="http://twitter.com/ContentChild">@ContentChild</a>(&#39;breakpointTag&#39;, { static: false, read: ElementRef }) breakpointTag: ElementRef;<br><a href="http://twitter.com/Output">@Output</a>() reached: EventEmitter&lt;boolean&gt; = new EventEmitter&lt;boolean&gt;();</pre><pre>constructor(private ngZone: NgZone, private commonService: CommonService) { }</pre><pre>ngOnInit() {<br>        <strong>// Run only in client side</strong><br>        if (!this.commonService.isBrowser())<br>            return;<br>        this._scrollEventBind = this.handler.bind(this);<br>        this.commonService.addListenerToWindowScroll(this._scrollEventBind);<br>    }</pre><pre>ngAfterViewInit() {<br>        // Run only in client side<br>        if (!this.commonService.isBrowser())<br>            return;</pre><pre>        <strong>// Delay the init function to avoid the access to DOM for perform better first load</strong><br>        if (&#39;requestIdleCallback&#39; in window) {<br>            // <a href="http://twitter.com/ts">@ts</a>-ignore<br>            window.requestIdleCallback(() =&gt; this._init());<br>        } else<br>        // For Internet Explorer<br>            this._init();</pre><pre>// Recalculate if browser window changes the dimensions<br>        this.$windowSize = this.commonService.$windowSize.pipe(debounceTime(50)).subscribe(() =&gt; {<br>            this.initOffsets();<br>        });<br>    }</pre><pre>_init() {<br>  this.initOffsets();</pre><pre>  if (this.checkBreakpoint(window.scrollY)) {<br>        this.reachedEmitted = true;<br>        this.reached.next(true);<br>      }<br>  }</pre><pre>initOffsets() {<br>  this.documentHeight = this.commonService.getHeight();</pre><pre>  if (this.breakpointTag) {<br>      this.breakpointOffsetTop =        this.findPos(this.breakpointTag.nativeElement)[1];<br>     }<br> }</pre><pre>handler (event) {<br>  const scrollY = event.currentTarget.pageYOffset;</pre><pre>  if (!this.reachedEmitted) {</pre><pre>  // Tag reached!<br>     if (this.checkBreakpoint(scrollY)) {<br>         this.reachedEmitted = true;</pre><pre><strong>// Necessary due scroll event is captured outside angular change detection</strong><br>         this.ngZone.run(() =&gt; {<br>              this.reached.next(true);<br>            });<br>         }<br>        }<br>    }</pre><pre>checkBreakpoint(scrollTop) {<br>        return scrollTop &gt; this.breakpointOffsetTop - this.documentHeight;<br>    }</pre><pre>findPos(obj) {<br>        let curleft = 0;<br>        let curtop = 0;<br>        if (obj.offsetParent) {<br>            do {<br>                curleft += obj.offsetLeft;<br>                curtop += obj.offsetTop;<br>            } while (obj = obj.offsetParent);<br>        }<br>        return [curleft, curtop];<br>    }</pre><pre>ngOnDestroy() {<br> if (!this.commonService.isBrowser())<br>            return;</pre><pre>this.commonService.removeListenerToWindowScroll(this._scrollEventBind);<br> this.$windowSize.unsubscribe();<br> }<br>}</pre><p>Let’s create a common service where you can manage the addition / removal of a scroll event and the current size of the browser window</p><pre><strong>common.service.ts</strong></pre><pre>import {Injectable, Inject, PLATFORM_ID, NgZone} from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br>import {isPlatformBrowser} from &#39;<a href="http://twitter.com/angular/common">@angular/common</a>&#39;;<br>import {Subject} from &#39;rxjs&#39;;</pre><pre><a href="http://twitter.com/Injectable">@Injectable</a>()<br>export class CommonService {<br>  private currentWidth = 0;<br>  private currentHeight = 0;</pre><pre>private isBrowserPlatform: boolean;</pre><pre>public $windowSize = new Subject&lt;Object&gt;();</pre><pre>passiveSupported = false;<br>passiveSupportedTested = false;<br>private eventOptions: boolean | {capture?: boolean, passive?: boolean};</pre><pre>scrollCallbacks = []; // Holds all window scroll callbacks for disable they when needed</pre><pre>constructor(<a href="http://twitter.com/Inject">@Inject</a>(PLATFORM_ID) platformId: Object, private ngZone: NgZone) {<br>    this.isBrowserPlatform = isPlatformBrowser(platformId);<br>  }</pre><pre>isBrowser(): boolean {<br>    return this.isBrowserPlatform;<br>  }</pre><pre>getWidth() {<br>    return this.currentWidth;<br>  }</pre><pre>getHeight() {<br>    return this.currentHeight;<br>  }</pre><pre>setDeviceDimensions(width, height) {<br>    this.currentWidth = width;<br>    this.currentHeight = height;<br>  }</pre><pre>addListenerToWindowScroll(callback) {<br>    if (!this.isBrowser())<br>      return;<br>    if (!this.passiveSupportedTested) {<br>      this.passiveSupportedTested = true;</pre><pre>       try {<br>        window.addEventListener(&#39;test&#39;, null,<br>          Object.defineProperty({}, &#39;passive&#39;,<br>            {<br>              get: function () {<br>                this.passiveSupported = true;<br>              }<br>            }));</pre><pre>       } catch (err) {}<br>    }<br>    if (this.passiveSupported) {<br>      this.eventOptions = {<br>        capture: true,<br>        passive: true<br>      };<br>    } else {<br>      this.eventOptions = true;<br>    }</pre><pre><strong>// Necessary for avoid a change detection on each scroll event</strong><br>    this.ngZone.runOutsideAngular(() =&gt; {<br>      this.scrollCallbacks.push(callback);<br>      window.addEventListener(&#39;scroll&#39;, callback, &lt;any&gt;this.eventOptions);<br>    });<br>  }</pre><pre>removeListenerToWindowScroll(handler) {<br>    for (let i = 0; i &lt; this.scrollCallbacks.length; i++)<br>      if (handler === this.scrollCallbacks[i]) {<br>        this.scrollCallbacks.splice(i, 1);<br>        break;<br>      }<br>    window.removeEventListener(&#39;scroll&#39;, handler, &lt;any&gt;this.eventOptions);<br>  }<br>}</pre><p>Let’s create a service to load a component of a module</p><pre><strong>loadLazyModule.service.ts</strong></pre><pre>import {Compiler, Injectable, NgModuleFactory} from &quot;<a href="http://twitter.com/angular/core">@angular/core</a>&quot;;</pre><pre><a href="http://twitter.com/Injectable">@Injectable</a>({providedIn: &#39;root&#39;})<br>export class LoadLazyModuleService {<br>    myModuleComponents;</pre><pre>constructor(private compiler: Compiler) {<br>    }</pre><pre>load() {<br>        return Promise.all([import(&#39;./my.module&#39;)])<br>            .then(m =&gt; m[0].MyModule)<br>            .then((modalModule) =&gt; {<br>                this.myModuleComponents = modalModule.components;<br>                if (modalModule instanceof NgModuleFactory) {<br>                    return modalModule;<br>                } else {<br>                    return this.compiler.compileModuleAsync(modalModule);<br>                }<br>            })<br>            .then(factory =&gt; {<br>                return {components: this.myModuleComponents};<br>            });<br>    }<br>}</pre><p>Let’s create a module that contains a component that we want to show on the page</p><pre><strong>my.module.ts</strong></pre><pre>import {NgModule} from &quot;<a href="http://twitter.com/angular/core">@angular/core</a>&quot;;<br>import {LazyComponent} from &quot;./lazy.component&quot;;</pre><pre><a href="http://twitter.com/NgModule">@NgModule</a>({<br>    declarations: [LazyComponent]<br>})<br>export class MyModule {<br>    static components = {lazyComponent: LazyComponent};<br>}</pre><p>Let’s create the lazy component</p><pre><strong>lazy.component.ts</strong></pre><pre>import {Component} from &quot;<a href="http://twitter.com/angular/core">@angular/core</a>&quot;;</pre><pre><a href="http://twitter.com/Component">@Component</a>({<br>    selector: &#39;app-lazy&#39;,<br>    template: `&lt;div style=&quot;color: red&quot;&gt;LAZY COMPONENT&lt;/div&gt;`<br>})</pre><pre>export class LazyComponent {}</pre><p>Use the directive on a page</p><pre><strong>app.component.html</strong></pre><pre>&lt;div tagReached (reached)=&quot;belowTagReached($event)&quot;&gt;<br>    &lt;div style=&quot;height: 800px; text-align: center; border: 3px solid blue;&quot;&gt;<br>        &lt;br&gt;<br>        ABOVE<br>        &lt;br&gt;<br>        THE<br>        &lt;br&gt;<br>        FOLD<br>        &lt;br&gt;<br>        CONTENT<br>    &lt;/div&gt;</pre><pre>&lt;div <strong>#breakpointTag</strong>&gt;<br>        &lt;div style=&quot;text-align: center; border: 3px solid yellow;&quot;&gt;<br>            BELOW<br>            &lt;br&gt;<br>            THE<br>            &lt;br&gt;<br>            FOLD<br>            &lt;br&gt;<br>            CONTENT<br>            &lt;br&gt;<br>            <strong>&lt;ng-template [ngComponentOutlet]=&quot;lazyComponent&quot;&gt;&lt;/ng-template&gt;</strong><br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;</pre><p>We capture the event in the component and also add a listener for the browser size change event</p><pre><strong>app.component.ts</strong></pre><pre>import {Component, HostListener, NgZone, OnDestroy, Type} from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;</pre><pre>import {CommonService} from &#39;../common.service&#39;;<br>import {LoadLazyModuleService} from &quot;./loadLazyModule.service&quot;;<br>import {LazyComponent} from &quot;./lazy.component&quot;;</pre><pre><a href="http://twitter.com/Component">@Component</a>({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.scss&#39;]<br>})<br>export class AppComponent implements OnDestroy {</pre><pre>// Window resize listener<br>  <a href="http://twitter.com/HostListener">@HostListener</a>(&#39;window:resize&#39;, [&#39;$event&#39;])<br>  onResize(event) {<br>    const widthChanged = this.commonService.getWidth() !== event.target.innerWidth;<br>    const heightChanged = this.commonService.getHeight() !== event.target.innerHeight;</pre><pre>this.commonService.setDeviceDimensions(event.target.innerWidth, event.target.innerHeight);<br>    this.commonService.$windowSize.next({width: event.target.innerWidth, height: event.target.innerHeight,<br>      widthChanged, heightChanged});<br>  }</pre><pre>lazyContent = false;<br>lazyComponent: Type&lt;LazyComponent&gt;;<br>destroyed = false;</pre><pre>constructor(private commonService: CommonService,<br>              private ngZone: NgZone, private loadLazyModule: LoadLazyModuleService) {</pre><pre>// Set the first window size<br>    if (commonService.isBrowser()) {<br>      this.commonService.setDeviceDimensions(window.innerWidth, window.innerHeight);<br>      this.commonService.$windowSize.next({width: window.innerWidth, height: window.innerHeight});<br>    } else<br>      // Force to be a smartphone (Moto G4) when SSR<br>      this.commonService.setDeviceDimensions(360, 640);<br>  }</pre><pre><strong>belowTagReached</strong>(event) {<br>    if (event &amp;&amp; !this.lazyContent) {<br>      this.ngZone.run(() =&gt; {<br>        console.log(&#39;reached&#39;);<br>        this.lazyContent = true;<br>        this.loadLazyModule.load().then((module) =&gt; {<br>          if (!this.destroyed)<br>            this.lazyComponent = module.components.lazyComponent;<br>        });<br>     });<br>    }<br>  }</pre><pre>ngOnDestroy(): void {<br>    this.destroyed = true;<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*443IYH9GEN7Cv0YjqZjzvQ.gif" /><figcaption>Lazy component loaded when “below the fold” was reached</figcaption></figure><p>This technique is also very useful to acquire scores for various benchmarks such as Lighthouse and others and therefore increase the SEO rank.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ef87559c867" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/angular-optimisation-load-content-below-the-fold-8ef87559c867">Angular optimisation: Load content below the fold</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular VS Lighthouse — Part 3]]></title>
            <link>https://medium.com/geekculture/angular-vs-lighthouse-part-3-848761a629f0?source=rss-34a7c2467e79------2</link>
            <guid isPermaLink="false">https://medium.com/p/848761a629f0</guid>
            <category><![CDATA[angular-first-page-load]]></category>
            <category><![CDATA[page-load-time]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[page-speed]]></category>
            <category><![CDATA[lighthouse]]></category>
            <dc:creator><![CDATA[Francesco Cantarella]]></dc:creator>
            <pubDate>Thu, 13 May 2021 10:24:19 GMT</pubDate>
            <atom:updated>2021-05-17T08:23:38.779Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular VS Lighthouse — Part 3</h3><p>Tips &amp; Tricks to increase your score.</p><p>This is part 3 of some useful tips and tricks to increase Lighthouse score and thereby reduce first page load time. You can find Part 1 <a href="https://medium.com/geekculture/angular-vs-lighthouse-part-1-27a9ac6584f"><strong>here</strong></a><strong> </strong>and Part 2 <a href="https://medium.com/geekculture/angular-vs-lighthouse-part-2-1ae627ca9aab"><strong>here</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*LtCLhVq2W4mfx8atI83FKw.png" /></figure><h4>High</h4><p>If your project needs to download an external file translation (like using <a href="http://twitter.com/ngx">@ngx</a>-translate and <a href="http://twitter.com/ngx">@ngx</a>-translate/HTTP-loader and a .json translation file) then include this file into main.js bundle.</p><p>Without this technique, after Angular has started, the browser repaints the entire page when the download of the translation file is complete. So you will have a double page re-paint / re-layout that can cause a Cumulative Layout Shift (CLS) too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4sHZ4mo2diaSJZ0NMGDixA.png" /><figcaption>Download translation file after Angular was started. Between SSR (server side rendering) and CSR (client side rendering) there are no translations provided so for each key there is a “<strong>…</strong>” instead</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*FgIN50NqZ6rwGTIzhYIgbw.png" /><figcaption>Relative Lighthouse penalty in score and CLS</figcaption></figure><p>For include a translation file into main.js bundle follow these steps:<br><strong>1)</strong> Create an environment file under environments folder for convenience:</p><pre><strong>env_lang.ts</strong></pre><pre>export const env_lang = {<br>  defaultLanguage: &#39;en&#39;,<br>  inlineTranslations: require(&#39;../assets/i18n/en.json&#39;)<br>};</pre><p><strong>2)</strong> Create a service that implements TranslateLoader:</p><pre><strong>language-loader.ts</strong></pre><pre>const translations = env_lang.inlineTranslations;</pre><pre><a href="http://twitter.com/Injectable">@Injectable</a>({providedIn: &#39;root&#39;})<br>export class LanguageLoader implements TranslateLoader {<br>  constructor(private http: HttpClient) {}</pre><pre>getTranslation(lang: string) {<br>    if (translations &amp;&amp; lang === env_lang.defaultLanguage) {<br>      return of(translations);<br>    } else {<br>      return this.http.get(`./assets/i18n/${lang}.json`);<br>    }<br>  }<br>}</pre><p><strong>3)</strong> Provide LanguageLoader service into TranslateModule configuration (in app module imports):</p><pre><strong>app.module.ts</strong></pre><pre>imports: [<br>...<br> TranslateModule.forRoot({<br>  loader: {<br>    provide: TranslateLoader,<br>    useExisting: <strong>LanguageLoader</strong>,<br>    deps: [PLATFORM_ID, HttpClient]<br>  }<br>   })<br>...<br>]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*XgXM0HdMHmauBH75Nt8-Mg.png" /><figcaption>Translation file included into main causes no difference between SSR and CSR</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*MULBFcSjhnxOTlymSfTVXQ.png" /><figcaption>No CLS! No wait for download another file! +10 points!</figcaption></figure><p>If your translation file is too large, try to include only the subset necessary for your optimized page and delay the download of the full file.<br>This is a not simple task but it’s very important to increase the score. If anyone is interested in how to implement it please leave a comment and I will prepare a dedicated article.</p><p><strong>NOTE: </strong>In general, CLS can occur when loading the contents of a &lt;div&gt; (or similar) it changes the height or width of the div itself, so try to set a fixed size. <br>CLS can also occur when the font changes the size of the div.</p><h4>Low/Medium</h4><p>Often we organize and group the code for one topic, and it is a good practice. But if the page that we want to perform better use only a part then we must split into 2 different groups: one only for the minimum necessary, and one for the rest.<br>If another page use only a part of the first group the ideal is to split another time. This process can be done indefinitely, but it is at your discretion to repeat it several times as you will lose some ease in development phase.<br>This problem typically occurs in services where we put a lot of methods concerning a problem domain.</p><h4>Low</h4><p>Below you will find several small tips.</p><ul><li>Remove old browser support:</li></ul><pre><strong>.browserslistsrc</strong></pre><pre>&gt; 0.5%<br>last 2 versions<br>Firefox ESR<br>not dead<br><strong>IE 11 // Or remove totally IE support</strong></pre><ul><li>Try to remove white spaces into HTML:</li></ul><pre><strong>tsconfig.app.json</strong></pre><pre>{<br>  ...<br>  &quot;angularCompilerOptions&quot;: {<br>    <strong>&quot;preserveWhitespaces&quot;: false</strong><br>  }<br>  ...<br>}</pre><ul><li>Wrong import of rxjs class:</li></ul><pre><strong>Bad</strong><br>import {Subscription} from &#39;rxjs/index&#39;;</pre><pre><strong>Good</strong><br>import {Subscription} from &#39;rxjs&#39;;</pre><ul><li>If you have a large lookup table then split each key in a separate “export const”, and after generate one file per key:</li></ul><pre><strong>lookup_data.ts</strong></pre><pre>export const features = {<br>  &#39;feature1&#39; : 1,<br>  &#39;feature2&#39; : 2,<br>  ...<br>};<br>export const status = {<br>  &#39;new&#39; : 0,<br>  &#39;active&#39; : 1,<br>  &#39;closed&#39; : 3,<br>  ...<br>};<br>...</pre><p>Create a script for easily generate files:</p><pre><strong>generate_keys_file.ts</strong></pre><pre>const fs = require(&#39;fs-extra&#39;);<br>import * as datas from &#39;./src/app/shared/lookup_data&#39;;</pre><pre>Object.keys(datas).map(value =&gt; {<br>  fs.writeFileSync(&#39;./src/app/shared/&#39; + value + &#39;.ts&#39; ,<br>    &#39;export const &#39; + value + &#39; = &#39; + JSON.stringify(datas[value]) + &#39;;&#39;, {encoding: &#39;utf-8&#39;});<br>});</pre><p>After running this script you will have the <strong>features.ts</strong>, <strong>status.ts</strong> (etc) files so that you can only import what you need.</p><ul><li>If you use moment js probably you don’t need his locales, so exclude they creating a webpack config file:</li></ul><pre><strong>extra-webpack.config.ts</strong></pre><pre>const webpack = require(&#39;webpack&#39;);<br>module.exports = {<br>  plugins: [<br>    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),<br>  ]<br>};</pre><p>Modify the angular.json file:</p><pre><strong>angular.json</strong></pre><pre>{<br> ...<br>  &quot;projects&quot;: {<br>    &quot;myproject&quot;: {<br>      ...<br>      &quot;architect&quot;: {<br>        &quot;build&quot;: {<br>          &quot;builder&quot;: &quot;<a href="http://twitter.com/angular">@angular</a>-builders/custom-webpack:browser&quot;,<br>          &quot;options&quot;: {<br>            &quot;customWebpackConfig&quot;: {<br>              &quot;path&quot;: &quot;./extra-webpack.config.js&quot;,<br>              &quot;mergeStrategies&quot;: {<br>                &quot;loaders&quot;: &quot;replace&quot;<br>              },<br>              &quot;replaceDuplicatePlugins&quot;: true<br>            }<br>         }<br>   ...<br>}</pre><p>Lighthouse is in continuous development and over time has changed both the metrics and the relative scores and therefore also the page optimization process never ends.<br>I hope I have been helpful with these suggestions, and I invite you to leave comments and / or clarifications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=848761a629f0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/angular-vs-lighthouse-part-3-848761a629f0">Angular VS Lighthouse — Part 3</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular VS Lighthouse — Part 2]]></title>
            <link>https://medium.com/geekculture/angular-vs-lighthouse-part-2-1ae627ca9aab?source=rss-34a7c2467e79------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ae627ca9aab</guid>
            <category><![CDATA[page-load-time]]></category>
            <category><![CDATA[page-speed]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[lighthouse]]></category>
            <category><![CDATA[page-load-optimisation]]></category>
            <dc:creator><![CDATA[Francesco Cantarella]]></dc:creator>
            <pubDate>Sat, 01 May 2021 18:30:14 GMT</pubDate>
            <atom:updated>2021-05-13T10:26:30.191Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular VS Lighthouse — Part 2</h3><h4>Tips &amp; Tricks to increase your score.</h4><p>This is part 2 of some useful tips and tricks to increase Lighthouse score and thereby reduce first page load time. You can find Part 1 <a href="https://francesco-cantarella.medium.com/angular-vs-lighthouse-part-1-27a9ac6584f"><strong>here</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*LtCLhVq2W4mfx8atI83FKw.png" /></figure><h4><strong>High</strong></h4><p>To achieve a good score we have to reduce as much as possible the code elaboration like heavy task or heavy DOM manipulation.</p><p>For example: if we have a list where there is a price with a currency symbol we easily write the following code:</p><pre><strong>app.component.ts<br></strong>...</pre><pre>list = [{name: &#39;item 1&#39;, price: &#39;50 &amp;euro;&#39;}, {name: &#39;item 2&#39;, price: &#39;70 &amp;euro;&#39;}];</pre><pre>app.component.html<br>...<br>&lt;div *ngFor=&quot;let item of list&quot;&gt;<br> &lt;div&gt;Price &lt;span [innerHTML]=&quot;item.price&quot;&gt;&lt;/span&gt;&lt;/div&gt;<br>&lt;/div&gt;</pre><p>If we have a list of 50 items we can lose even 4–5 points!<br>So the optimized code can be:</p><pre><strong>app.component.ts</strong><br>...</pre><pre>list = [{name: &#39;item 1&#39;, price: &#39;50 <strong>€</strong>&#39;}, {name: &#39;item 2&#39;, price: &#39;70 <strong>€</strong>&#39;}];</pre><pre>app.component.html<br>...<br>&lt;div *ngFor=&quot;let item of list&quot;&gt;<br> &lt;div&gt;{{item.name}} - price &lt;span <strong>[textContent]</strong>=&quot;item.price&quot;&gt;&lt;/span&gt;&lt;/div&gt;<br>&lt;/div&gt;</pre><p>When we use <strong>[innerHTML]</strong> Angular must parse a template and apply a DOM sanitizer. When we use <strong>[textContent]</strong> Angular only inserts a text, so try to avoid the use of ‘innerHTML’ as much as possible.</p><h4><strong>Low</strong></h4><p>Another example: we have a list and we want to include a relative JSON-ld script for each item.</p><p>If we are using SSR then we can avoid calculating 2 times the JSON-ld. Just use <a href="https://angular.io/api/platform-browser/TransferState"><strong>TransferState</strong></a>.</p><pre><strong>app.component.ts</strong><br>const LIST_JSONLD = makeStateKey(&#39;LIST_JSONLD&#39;);</pre><pre>...<br>constructor(private seoService: SeoService, private state: TransferState) {}</pre><pre>ngOnInit() {<br> if (this.isSSR) { // Calculate json-ld only in server side<br>  // Long list<br>  const list = [{field1: &#39;...&#39;}...];<br>  this.listJsonLd = this.seoService.getListJsonLd(list);<br>  this.state.set(LIST_JSONLD, this.listJsonLd as any);<br> } else {<br>  this.listJsonLd = this.state.get(LIST_JSONLD, null as any);<br>  this.state.remove(LIST_JSONLD);<br> }<br>}</pre><pre><strong>seo.service.ts</strong><br>...<br>getListJsonLd(array) {<br>    if (array) {<br>      const jsonldArray = [];<br>      forEach(array, (value) =&gt; {<br>        if (value &amp;&amp; value.fields) {<br>          const jsonld = this.getItemJsonLd(value);<br>          if (jsonld)<br>            jsonldArray.push(jsonld);<br>        }<br>      });<br>      return jsonldArray;<br>    }<br>  }</pre><pre>getItemJsonLd(value) {  <br>...<br>// Long calculations<br>}<br></pre><pre><strong>app.component.html</strong><br>...<br>&lt;app-json-ld [json]=&quot;listJsonLd&quot;&gt;&lt;/app-json-ld&gt;</pre><h4><strong>High</strong></h4><p>Typically an angular application is split into separate files based on routes where the ‘loadChildren’ parameter is used.<br>Then the main.js file will be loaded first, then Angular will start, then the router module will load the related route file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*lAUoNmEfiDUVwQlhxdL4yQ.png" /><figcaption>Using loadChildren route with module not included into the main bundle</figcaption></figure><p>With this approach, the browser performs serial calls making us lose 4–5 points.</p><p>This can be avoided by including the routed module into app.module so when compiled, the main.js will include the routed module file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*laZ_WbGpfJ9kjhJRd7h_Bg.png" /><figcaption>Using loadChildren route with the module included into the main bundle</figcaption></figure><p>But this can be done only for one routed module, else the main will grow too much. How can we do more than one route?</p><p>The trick is to compile a different application for each route needed.</p><p>This will drastically increase the compile-time, but it is the only option available to have this optimization.</p><p>Create an environment file that will be used for not optimized routes:</p><pre><strong>environment_optimized.ts</strong></pre><pre>export const environment_optimized = {<br>  preloadedModule: false,<br>  moduleName: undefined<br>};</pre><p>Create an environment file for each optimized route:</p><pre><strong>env_my_module.ts</strong></pre><pre>import {MyModule} from &#39;../app/my.module&#39;;</pre><pre>export const environment_optimized = {<br>  preloadedModule: [MyModule],<br>  moduleName: &#39;MyModule&#39;<br>};</pre><p>Add it to app module imports:</p><pre><strong>app.module.ts</strong></pre><pre>const imports: any = [<br> BrowserModule.withServerTransition({ appId: &#39;my-app&#39; }),<br> HttpClientModule<br> ...<br> ];<br> <br>if (environment_optimized.preloadedModule)<br>  imports.push(environment_optimized.preloadedModule);</pre><p>Add ‘moduleName’ property to the route, it can be useful later:</p><pre><strong>app-routing.module.ts</strong></pre><pre>const routes = [<br> {  path: &#39;my-route1&#39;,<br>  loadChildren: import(&#39;./my.module&#39;).then(m =&gt; m.MyModule),,<br>  data: {moduleName: &#39;MyModule&#39;}<br> }<br> ...<br>];</pre><p>Add a new configuration where the environment_optimized.ts file will be replaced:</p><pre><strong>angular.json</strong></pre><pre>...<br>  &quot;configurations&quot;: {<br>            &quot;production&quot;: {<br>              ...<br>            },<br>            &quot;mymodule&quot;: {<br>              &quot;outputPath&quot;: &quot;dist/mymodule&quot;,<br>              &quot;index&quot;: {<br>                &quot;input&quot;: &quot;src/index.html&quot;,<br>                &quot;output&quot;: &quot;index_mymodule.html&quot;<br>              },<br>              &quot;optimization&quot;: true,<br>              &quot;outputHashing&quot;: &quot;all&quot;,<br>              &quot;sourceMap&quot;: false,<br>              &quot;extractCss&quot;: true,<br>              &quot;namedChunks&quot;: false,<br>              &quot;aot&quot;: true,<br>              &quot;extractLicenses&quot;: true,<br>              &quot;vendorChunk&quot;: false,<br>              &quot;buildOptimizer&quot;: true,<br>              &quot;fileReplacements&quot;: [<br>                {<br>                  &quot;replace&quot;: &quot;src/environments/environment.ts&quot;,<br>                  &quot;with&quot;: &quot;src/environments/environment.prod.ts&quot;<br>                },                {<br>                  &quot;replace&quot;: &quot;src/environments/environment_optimized.ts&quot;,<br>                  &quot;with&quot;: &quot;src/environments/env_my_module.ts&quot;<br>                }<br>              ],<br>              &quot;serviceWorker&quot;: true<br>            }<br>          }<br>...</pre><p>Create a file where save index file to load relative to the route:</p><pre><strong>optimized_routes_config.js</strong><br>/**<br> *<br> * routeRegex: regular expression for run specific optimized index<br> * indexFileName: name of the specific index generated<br> * folder: folder where retrieve relative optimized files<br> */</pre><pre>module.exports = {<br>  config: [<br>    {<br>      routeRegex: [/^\/my-route1\//],<br>      indexFileName: &#39;index_mymodule.html&#39;,<br>      folder: &#39;mymodule&#39;<br>    }<br>  ]<br>};</pre><p>Modify the server.ts file to load the correct index for the requested optimized route or the default index:</p><pre><strong>server.ts</strong></pre><pre>import * as ORConfig from &#39;./optimized_routes_config&#39;;<br>...<br>const foundORIndex = [];</pre><pre>app.get(&#39;*&#39;, (req, res) =&gt; {<br>  let indexFileName = &#39;index&#39;;<br>  <br>  for (let i = 0; i &lt; ORConfig.config.length; i++) {<br>    for (let j = 0; j &lt; ORConfig.config[i].routeRegex.length; j++) {<br>      const pattern_index = new RegExp(ORConfig.config[i].routeRegex[j]);<br>      if (pattern_index.test(req.url)) {<br>        if (!foundORIndex[ORConfig.config[i].indexFileName])<br>          foundORIndex[ORConfig.config[i].indexFileName] = fs.existsSync(ORConfig.config[i].indexFileName);<br>        if (foundORIndex[ORConfig.config[i].indexFileName])<br>          indexFileName = ORConfig.config[i].indexFileName;<br>        break;<br>      }<br>    }<br>  }</pre><pre>res.render(indexFileName, {<br>    req, res},<br>    function (err, html) {<br>      res.send(html);<br>    }<br>  );<br>});</pre><p>For easy deployment, create a file that will copy all the route optimized .js files into the default dist directory.<br>Only the .js files and the index_xxxx.html must be copied because the ngsw.json (file created by the angular service worker ngsw) must be that of the default compilation.</p><pre><strong>deploy_optimized_routes.js</strong></pre><pre>const ORConfig = require(&#39;./optimized_routes_config&#39;);</pre><pre>const fs = require(&#39;fs-extra&#39;);</pre><pre>const path = require(&#39;path&#39;);</pre><pre>for (let i = 0; i &lt; ORConfig.config.length; i++) {<br>  let dirPath = path.resolve(&#39;dist/&#39; + ORConfig.config[i].folder); // path to your directory goes here<br>  let filesList;<br>  fs.readdir(dirPath, function(err, files){<br>    filesList = files.filter(function(e){<br>      return path.extname(e).toLowerCase() === &#39;.js&#39;<br>    });<br>    // console.log(filesList);<br>    filesList.forEach(file =&gt; {<br>      fs.copyFileSync(dirPath+ &#39;/&#39;+ file, &#39;dist/&#39; + file, err =&gt; {<br>        if (err)<br>          console.log(&#39;error copying file&#39;, file, err);<br>      });<br>    });<br>    fs.copyFileSync(dirPath + &#39;/&#39; + ORConfig.config[i].indexFileName, &#39;dist/&#39; + ORConfig.config[i].indexFileName, err =&gt; {<br>      if (err)<br>        console.log(&#39;error copying file&#39;, file, err);<br>    });<br>    fs.removeSync(dirPath);<br>  });<br>}</pre><p>Next week I will post Part 3 where there will be more interesting tips and tricks. Stay tuned and leave comments!</p><p><strong>Update</strong>: Part 3 is <a href="https://francesco-cantarella.medium.com/angular-vs-lighthouse-part-3-848761a629f0"><strong>here</strong></a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ae627ca9aab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/angular-vs-lighthouse-part-2-1ae627ca9aab">Angular VS Lighthouse — Part 2</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular VS Lighthouse — Part 1]]></title>
            <link>https://medium.com/geekculture/angular-vs-lighthouse-part-1-27a9ac6584f?source=rss-34a7c2467e79------2</link>
            <guid isPermaLink="false">https://medium.com/p/27a9ac6584f</guid>
            <category><![CDATA[angular-first-load]]></category>
            <category><![CDATA[page-load-time]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[lighthouse]]></category>
            <category><![CDATA[page-load-optimisation]]></category>
            <dc:creator><![CDATA[Francesco Cantarella]]></dc:creator>
            <pubDate>Mon, 19 Apr 2021 10:13:44 GMT</pubDate>
            <atom:updated>2021-05-08T09:51:16.531Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular VS Lighthouse — Part 1</h3><h4>Tips &amp; Tricks to increase your score.</h4><p>This article requires a good knowledge of Angular.</p><p>If your score is low despite having applied common optimization techniques such as well described <a href="https://faun.pub/44-quick-tips-to-fine-tune-angular-performance-9f5768f5d945"><strong>here</strong> </a>or <a href="https://medium.com/swlh/angular-performance-optimization-techniques-5b7ca0808f8b"><strong>here </strong></a>then read the techniques and tricks described in this series of articles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*LtCLhVq2W4mfx8atI83FKw.png" /></figure><p>In mobile (the most important test device) a my optimized page increased from 68 points to 96 points, and in desktop from 96 to 100 points. <br>This using Chrome 90 that fixes the LCP (Larget Contentful Paint) issue.<br>Another optimized page, and having used the Chrome 87, increased from 34 to 83 points in mobile test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*qGMM7D2OjuiBizR6_Krbhg.png" /></figure><p>Reach a good score on Lighthouse when using Angular is not simple as some articles describe.<br>Some articles show a 100 score points but it’s simple to reach this score on a project like an ‘Hello World’ page, or a project without 3rd party libraries, or a simple page…<br>The reality is different: it is common to have in a project multiple dependencies on third-party libraries, forms, shared logic accross pages, shared styles and so on…<br>So the optimization process for achieve a good score, and probably NOT a score of 100, is long and includes several steps.</p><p><strong>NOTE</strong>:<br>We will focus only on the pages that affect SEO ranking so the Lighthouse score is more important.<br>For other pages we can’t apply all the optimization presented in this guide.</p><p>The common principles (I called them <strong>5M</strong>) that I used during an optimization step are:</p><ul><li>minimum main bundle size: <br>It’s fundamental to reduce as much possible the size of the main.js file and the other first load files as .css, .json, .svg files.<br>The less data to upload the more points you will get!<br>Moreover, the less javascript to process the greater the increment will be!<br>It’s recommended to load under 1.5MB of javascript.</li><li>minimum code elaboration:<br>Code elaboration can impact significantly the score, so it’s desirable to perform minimum code elaboration, in both code script and DOM page.</li><li>minimum requests:<br>Reduce the number of requests necessary because the browser can perform only limited concurrent requests, else some of these will wait until a previous is complete.<br>We must avoid to think to perform only one very large request because it’s better to perform parallel request, for example load .css, .js, .jpg files separatly. <br>We also must avoid serial requests.</li><li>minimum components:<br>For every component used into the page, Angular must build and parse a DOM object, attach listeners on it and so on.<br>So load the only necessary component for build the page, as if it were a static page. Also avoid very deep components chain.</li><li>minimum styles:<br>Load only the styles used into the page, and put only minimum styles into global css file.</li></ul><p>I used ‘<strong>minimum</strong>’ term because each project is unique, so each project has different needs and priorities and therefore it is at your discretion to use some optimization techniques.<br>You must try to ‘minimize’ the resources required to meet the requirements of your pages, and sometimes you have to try to reach a good compromise between score and ease of development / maintainability.</p><p>Each suggestion is marked with the possible increase of the score (<strong>Low</strong>, <strong>Medium</strong>, <strong>High</strong>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cw92WhLGAKVqYl0hny8FaA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lQMEh7XXJI8OZ1T3OQ44jA.png" /><figcaption>Before optimizations</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*50QW8pDokyhgW-GBqXwULQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ftg3itR2_tUg_nyRJFss8A.png" /><figcaption>After optimizations</figcaption></figure><h4>High</h4><p>If you use some analytics scripts then delay it. You can choose to load these scripts after some user interactions or after X seconds (at least 3–4).<br>If you choose after X seconds you will lose sub X second report, but probably it’s not important.<br>Let’s see how to delay loading of Google Tag Manager (GTM) after Angular is started.<br><strong>NOTE</strong>: in development mode I prefer not to have a delayed GTM.</p><pre>main.ts<br>...<br>const tag_manager_key = &#39;&#39;;<br>document.addEventListener(&#39;DOMContentLoaded&#39;, () =&gt; {      <br>       // In production mode<br>       if (environment.production) {</pre><pre>window[&#39;dataLayer&#39;] = [];<br>         /** init gtm after 3500 seconds - this could be adjusted */<br>         setTimeout(initGTM, 3500);</pre><pre>/*       <br>   document.addEventListener(&#39;scroll&#39;, initGTMOnEvent);<br>   document.addEventListener(&#39;mousemove&#39;, initGTMOnEvent);<br>   document.addEventListener(&#39;touchstart&#39;, initGTMOnEvent);</pre><pre>   function initGTMOnEvent (event) {<br>           initGTM();<br>           event.currentTarget.removeEventListener(event.type, initGTMOnEvent); // remove the event listener that got triggered<br>         }*/</pre><pre>function initGTM () {<br>           if (window[&#39;gtmDidInit&#39;]) {<br>             return false;<br>           }<br>           window[&#39;gtmDidInit&#39;] = true; // flag to ensure script does not get added to DOM more than once.<br>           const script = document.createElement(&#39;script&#39;);<br>           script.type = &#39;text/javascript&#39;;<br>           script.async = true;<br>           script.onload = () =&gt; { window[&#39;dataLayer&#39;].push({ event: &#39;gtm.js&#39;, &#39;gtm.start&#39;: (new Date()).getTime(),<br>             &#39;gtm.uniqueEventId&#39;: 0 }); }; // this part ensures PageViews is always tracked<br>           script.src = &#39;<a href="https://www.googletagmanager.com/gtm.js?id=&#39;">https://www.googletagmanager.com/gtm.js?id=&#39;</a> + tag_manager_key;</pre><pre>document.head.appendChild(script);<br>         }<br>       }<br>       // In development mode<br>       else {         <br>     const scriptGTM = document.createElement(&#39;script&#39;);<br>     scriptGTM.innerHTML = &#39;(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({\&#39;gtm.start\&#39;:\n&#39; +<br>    &#39;new Date().getTime(),event:\&#39;gtm.js\&#39;});var f=d.getElementsByTagName(s)[0],\n&#39; +<br>    &#39;j=d.createElement(s),dl=l!=\&#39;dataLayer\&#39;?\&#39;&amp;l=\&#39;+l:\&#39;\&#39;;j.async=true;j.src=\n&#39; +<br>    &#39;\&#39;<a href="https://www.googletagmanager.com/gtm.js?id=\&#39;+i+dl;f.parentNode.insertBefore(j,f);\n&#39;">https://www.googletagmanager.com/gtm.js?id=\&#39;+i+dl;f.parentNode.insertBefore(j,f);\n&#39;</a> +<br>    &#39;})(window,document,\&#39;script\&#39;,\&#39;dataLayer\&#39;,\&#39;&#39; + tag_manager_key + &#39;\&#39;);&#39;;<br>     document.body.appendChild(scriptGTM);<br>       }<br>    <br>    platformBrowserDynamic().bootstrapModule(AppModule, {preserveWhitespaces: true})<br>           .catch(err =&gt; console.log(err));<br>});</pre><h4>High</h4><p>Remove from app.module and shared.module (tipical files) all the modules and components not strictly necessary, for example modals, autocomplete, uploaders utility and so on.<br>Let’s take an autocomplete field for example: we will make a fake input field and when it will receive a focus or click then we will load the autocomplete module and component.<br>We use ng-dynamic-component for inject dynamically a component and the typeahed module from ngx-bootstrap library.</p><p>Create a module that contains the autocomplete files:</p><pre>auto-complete.module.ts</pre><pre>import {NgModule} from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br>import {FormsModule} from &#39;<a href="http://twitter.com/angular/forms">@angular/forms</a>&#39;;<br>import {TypeaheadModule} from &#39;ngx-bootstrap/typeahead&#39;;<br>import {PositioningService} from &#39;ngx-bootstrap/positioning&#39;;</pre><pre>import {SearchAutoCompleteComponent} from &#39;../search/auto-complete/search-auto-complete.component&#39;;<br>import {SharedModule} from &#39;../shared.module&#39;;<br>import {SearchAutoCompleteService} from &#39;../search/auto-complete/search-auto-complete.service&#39;;</pre><pre><a href="http://twitter.com/NgModule">@NgModule</a>({<br>  imports: [<br>    FormsModule,<br>    SharedModule,<br>    TypeaheadModule.forRoot()<br>  ],<br>  declarations: [<br>    SearchAutoCompleteComponent<br>  ],<br>  exports: [<br>    SharedModule,<br>    FormsModule,<br>    TypeaheadModule,<br>    SearchAutoCompleteComponent,<br>  ],<br>  providers: [PositioningService, SearchAutoCompleteService ]</pre><pre>})<br>export class AutoCompleteModule {<br>  static components = {<br>    searchAutoComplete: SearchAutoCompleteComponent<br>  };<br>  static services = {<br>    searchAutoCompleteService: SearchAutoCompleteService<br>  };<br>}</pre><p>Create a service that will allow easy loading and use of the removed modules:</p><p><strong>NOTE</strong>: see how to map the related services of the module, so that they can also be used delayed.</p><pre>load-module.service.ts</pre><pre><a href="http://twitter.com/Injectable">@Injectable</a>({providedIn: &#39;root&#39;})<br>export class LoadModuleService {</pre><pre>autoCompleteModuleComponents;</pre><pre>constructor(private compiler: Compiler, private injector: Injector) {}</pre><pre>loadAutocompleteModule() {<br>    return import(&#39;../../shared/search/auto-complete.module&#39;)<br>      .then(m =&gt; m.AutoCompleteModule)<br>      .then((autoCompleteModule) =&gt; {<br>        this.autoCompleteModuleComponents = (autoCompleteModule).components;<br>        if (autoCompleteModule instanceof NgModuleFactory) {<br>          return autoCompleteModule;<br>        } else {<br>          return this.compiler.compileModuleAsync(autoCompleteModule);<br>        }<br>      })<br>      .then(factory =&gt; {<br>        const moduleRef = factory.create(this.injector);</pre><pre>        const searchAutoCompleteService: any =  moduleRef.injector.get((&lt;any&gt;factory.moduleType).services.searchAuto CompleteService);</pre><pre>        return {<br>          module: factory,<br>          injector : moduleRef.injector,<br>          services: {searchAutoCompleteService},<br>          components: this.autoCompleteModuleComponents};<br>      });<br>  }<br>}</pre><p>Component where is placed the (fake) input field:</p><pre>app.component.ts<br>...<br>showFakeInput = true;<br>searchAutoComplete: Type&lt;SearchAutoCompleteComponent&gt;;<br>moduleFactory;<br>loadingAutoCompleteModule = false;<br>SACinputs;<br>SACoutputs;<br>SAS;<br>SACinjector;</pre><pre>constructor(private loadModuleService: LoadModuleService) { }</pre><pre>...<br>loadAutocompleteModule() {<br>    if (this.loadingAutoCompleteModule)<br>      return;<br>    this.loadingAutoCompleteModule = true;<br>    this.SACinputs = {<br>      ...<br>    };<br>    this.SACoutputs = {<br>      searched: result =&gt; {<br>        ...<br>      },<br>    };<br>    this.loadModuleService.loadAutocompleteModule()<br>       .then(autoCompleteModule =&gt; {<br>          this.searchAutoComplete = autoCompleteModule.components.searchAutoComplete;<br>          this.moduleFactory = autoCompleteModule.module;<br>          this.SAS = autoCompleteModule.services.searchAutoCompleteService;<br>          this.SACinjector = autoCompleteModule.injector;<br>          this.showFakeInput = false;<br>          this.changeDetRef.markForCheck();<br>    });<br>  }</pre><p>Relative template file:</p><pre>app.component.html<br>...<br>&lt;div *ngIf=&quot;showFakeInput&quot;&gt;<br>  &lt;div class=&quot;form-group&quot;&gt;<br> &lt;input type=&quot;text&quot; name=&quot;asyncSelected&quot;  [placeholder]=&quot;type here...&quot;<br>     autocomplete=&quot;off&quot;<br>     disableautocomplete<br>     (click)=&quot;loadAutocompleteModule()&quot; (focus)=&quot;loadAutocompleteModule()&quot; [value]=&quot;&quot;&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;<br>&lt;ng-template [ngComponentOutlet]=&quot;searchAutoComplete&quot;<br>    [ndcDynamicInputs]=&quot;SACinputs&quot;<br>    [ndcDynamicOutputs]=&quot;SACoutputs&quot;<br>    [ngComponentOutletInjector]=&quot;SACinjector&quot;&gt;<br>&lt;/ng-template&gt;</pre><p>With this technique we only load the ng-dynamic-component library and little pieces of code saving a lot of kb and increasing a lot of Lighthouse score.<br>Apply this technique <strong>as much as possible</strong>, for example for elements below the folds, user menu, modals, maps, charts, and so on.<br>Try to make the above the fold part as if it were a static page or at least with very little processing.</p><h4>Low</h4><p>If you have an image server on your domain, add it to the index.html using ‘preconnect’:</p><pre>&lt;link href=’<a href="https://image.my-site.com&/#39;">https://image.my-site.com&#39;</a> rel=’preconnect’ crossorigin&gt;</pre><p>Do the same if you load external font, and load it with rel=’preload’:</p><pre>&lt;link rel=&quot;dns-prefetch&quot; href=&quot;<a href="https://fonts.googleapis.com/">https://fonts.googleapis.com</a>&quot;&gt;</pre><pre>&lt;link rel=&quot;preload&quot; as=&quot;style&quot; onload=&quot;this.onload=null; this.rel=&#39;stylesheet&#39;;&quot; href=&quot;<a href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400&amp;display=swap">https://fonts.googleapis.com/css?family=Source+Sans+Pro:400&amp;display=swap</a>&quot;&gt;</pre><h4>Low</h4><p>Use a more performante function for cloning object instead of cloneDeep of lodash (only if you <strong>don’t</strong> need to copy functions too).</p><pre>export function deepCopy(o) {<br>  let newobject = {};<br>  if (o !== undefined &amp;&amp; o !== null &amp;&amp; o.constructor)<br>    newobject = new o.constructor();<br>  return typeof o === &#39;object&#39; &amp;&amp; o !== null ?<br>    (Array.isArray(o) ?             <br>        o.map(e =&gt; deepCopy(e)) : <br>        Object.keys(o).reduce(<br>          (r, k) =&gt; (r[k] = deepCopy(o[k]), r), newobject <br>        )<br>    ) :<br>    o;<br>}</pre><p>Next week I will post Part 2 where there will be more interesting tips and tricks. Stay tuned and leave comments!</p><p><strong>Update</strong>: Part 2 is <a href="https://francesco-cantarella.medium.com/angular-vs-lighthouse-part-2-1ae627ca9aab"><strong>here</strong></a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27a9ac6584f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/angular-vs-lighthouse-part-1-27a9ac6584f">Angular VS Lighthouse — Part 1</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Load Configuration Environment Variables into Angular Efficiently When Using SSR]]></title>
            <link>https://medium.com/geekculture/load-configuration-environment-variables-into-angular-efficiently-when-using-ssr-6474c34bb675?source=rss-34a7c2467e79------2</link>
            <guid isPermaLink="false">https://medium.com/p/6474c34bb675</guid>
            <category><![CDATA[angular-ssr-environment]]></category>
            <category><![CDATA[angular-json-environment]]></category>
            <category><![CDATA[angular-environment]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Francesco Cantarella]]></dc:creator>
            <pubDate>Mon, 05 Apr 2021 14:29:12 GMT</pubDate>
            <atom:updated>2021-04-12T23:12:00.637Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*WsmYf2gFfPbQyQBCp49fjg.png" /></figure><p>Often is useful to load environment variables without rebuilding the project, like when deploying the same project to different servers (or docker instances) with a different configuration.</p><p>The target is to load the config WITHOUT wait and perform an HTTP request.<br>This technique avoid a negative impact on the first load page (did someone say Lighthouse?).</p><p>So the best strategy is to load the environment variables when run the server-side rendering (SSR) node process and store they into the index.html file.<br>See how to do it:</p><ol><li>Put the environment variables into a json file, and save as env.json into assets folder:</li></ol><pre>env.json</pre><pre>{<br> &quot;apiUrl&quot;: &quot;<a href="https://example.com/">https://example.com</a>&quot;,<br> &quot;version&quot;: &quot;1.1&quot;,<br> …<br>}</pre><p>2. Modify the index.html placing a placeholder for easily substitute the variables:</p><pre>index.html</pre><pre>&lt;html&gt;<br> &lt;head&gt;<br> &lt;!-- ENV BEGIN --&gt;<br> &lt;!-- ENV END --&gt;<br> …<br> &lt;/head&gt;<br>&lt;/html&gt;</pre><p>3. Load and substitute the variables into index.html file when run the node SSR process:</p><pre>server.ts</pre><pre>...<br>const injectEnvInline = function (filename, envs) {<br> let _template_index = fs.readFileSync(filename).toString();</pre><pre>// Find env script link<br> const env_begin_position = _template_index.indexOf(&#39;&lt;!-- ENV BEGIN --&gt;&#39;);<br> const env_end_position = _template_index.indexOf(&#39;&lt;!-- ENV END --&gt;&#39;);<br> const env_link = _template_index.substring(env_begin_position, env_end_position);<br> <br> // Remove env script link and injecting inline environment variables_template_index = _template_index.replace(env_link, envs);<br> fs.writeFileSync(filename , _template_index, {encoding: &#39;utf-8&#39;});<br>};</pre><pre>// Read environment settings<br>const settings = JSON.parse(fs.readFileSync(&#39;assets/env.json&#39;).toString());<br>const env: any = [];<br>let inline_env = &#39;&lt;!-- ENV BEGIN --&gt;&lt;script&gt;window[\&#39;_env\&#39;] = []; &#39;;<br>for (const key in settings) {<br> if (settings.hasOwnProperty(key)) {<br> env[key] = settings[key];<br> inline_env += &#39;window[\&#39;_env\&#39;].&#39; + key + &#39;= \&#39;&#39; + settings[key] + &#39;\&#39;; &#39;;<br> }<br>}<br>inline_env += &#39;&lt;/script&gt;&#39;;</pre><pre>injectEnvInline(&#39;index.html&#39;, inline_env);</pre><p>4. Only if we are using angular service worker (ngsw):<br>Due we modified the index.html file then we must update his hash stored into ngsw.json file.</p><pre>server.ts</pre><pre>...<br>const changeIndexHtmlHash = function (filename, newHash: string) {<br>  let _template_ngsw = fs.readFileSync(filename).toString();</pre><pre>// Find index.html hash row<br>  const index_begin_position = template_ngsw.lastIndexOf(&#39;&quot;/index.html&quot;: &quot;&#39;);<br>  const index_end_position = index_begin_position + 57;<br>  const new_index_hash = _template_ngsw.substring(index_begin_position, index_end_position);</pre><pre>_template_ngsw = _template_ngsw.replace(new_index_hash, &#39;&quot;/index.html&quot;: &quot;&#39; + newHash + &#39;&quot;&#39;);<br>  fs.writeFileSync(filename , _template_ngsw, {encoding: &#39;utf-8&#39;});<br>};</pre><pre>// Change index.html hash into ngsw.json<br>const shasum = crypto.createHash(&#39;sha1&#39;);<br>const indexHtmlStream = fs.ReadStream(&#39;./index.html&#39;);<br>indexHtmlStream.on(&#39;data&#39;, function(d) { shasum.update(d); });<br>indexHtmlStream.on(&#39;end&#39;, function() {<br>  const newHash = shasum.digest(&#39;hex&#39;);<br>  changeIndexHtmlHash(&#39;ngsw.json&#39;, newHash);<br>});</pre><p>5. Pass the variables and inject they into the relative service when running the server side mode:</p><pre>server.ts</pre><pre>...<br>app.get(&#39;*&#39;, function(req, res) {<br> res.render(&#39;index&#39;, {<br>  req, res, providers: [<br>   { provide: &#39;envSettings&#39;, useValue: env }<br>   ]<br>  }<br> });<br>});</pre><p>6. Create the env service file:</p><pre>env.service.ts</pre><pre>import {Inject, Injectable, Optional} from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;</pre><pre>export interface IEnvService {<br>  &quot;apiUrl&quot;: string;<br>  &quot;version&quot;: string;<br>}</pre><pre><a href="http://twitter.com/Injectable">@Injectable</a>({providedIn: &#39;root&#39;})<br>export class EnvService {<br>  settings: IEnvService = {} as null;<br>  constructor(<a href="http://twitter.com/Inject">@Inject</a>(&#39;envSettings&#39;) <a href="http://twitter.com/Optional">@Optional</a>() private envSettings?: any) {<br>    if (envSettings) {<br>      this.settings = envSettings;<br>    }<br>  }<br>}</pre><p>7. Inject the env service into app.server.module.ts file:</p><pre>...<br>providers: [EnvService]</pre><p>8. Load the environment variables when running the client side mode:<br>(Note: we load the env.json file when running in <strong>development</strong> mode and read the window[‘_env’] keys when running in <strong>production</strong> mode)</p><pre>main.ts</pre><pre>...<br>document.addEventListener(&#39;DOMContentLoaded&#39;, () =&gt; {</pre><pre>const start = (settings) =&gt; {<br>         // environment.settings = settings.settings;<br>         platformBrowserDynamic([{provide: &#39;envSettings&#39;, useValue: settings}])<br>   .bootstrapModule(AppModule, {preserveWhitespaces: true})<br>           .catch(err =&gt; console.log(err));<br>       };</pre><pre>let _env: any = {};<br>       // In <strong>production</strong> mode<br>       if (window &amp;&amp; window[&#39;_env&#39;] !== undefined) {<br>         const browserWindow = window;<br>         const browserWindowEnv = browserWindow[&#39;_env&#39;] || {};</pre><pre>// Assign environment variables from browser window to env<br>         for (const key in browserWindowEnv) {<br>           if (browserWindowEnv.hasOwnProperty(key)) {<br>             _env[key] = window[&#39;_env&#39;][key];<br>           }<br>         }</pre><pre>start(_env);<br>       }<br>       // In <strong>development</strong> mode<br>       else {<br>         const xhttp = new XMLHttpRequest();<br>         xhttp.onreadystatechange = function () {<br>           if (this.readyState === 4 &amp;&amp; this.status === 200) {<br>             const response: IEnvService = JSON.parse(xhttp.responseText);<br>             _env = response;</pre><pre>start(_env);<br>           }<br>         };<br>         xhttp.open(&#39;GET&#39;, &#39;assets/env.json&#39;, true);<br>         xhttp.send();<br>       }<br>});</pre><p>9. Use env service whenever you want:</p><pre>app.module.ts</pre><pre>import {EnvService} from &#39;./env.service&#39;;<br>...<br>constructor(private envService: EnvService) {}</pre><pre>foo() {<br> console.log(&#39;version&#39;, this.envService.settings.version);<br>}</pre><p>With these simple steps we have reached the target to load environment variables without rebuild the project, without an HTTP request <br>and use the same file configuration (env.json) during development process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6474c34bb675" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/load-configuration-environment-variables-into-angular-efficiently-when-using-ssr-6474c34bb675">Load Configuration Environment Variables into Angular Efficiently When Using SSR</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>