1

Is there a way we can load external scripts such as those provided by 3rd party websites after our main application scripts which are built by Angular 8? We have tried placing them at the end of the index.html but these are still loading before main.js, polyfill.js and other app scripts after being built using ng -prod

Lucas Gomez
  • 145
  • 1
  • 3
  • 12

1 Answers1

1

To load an external script after Angular App finished initialization you could add it "manually" by adding a <script> node in DOM.

loadScript() {
   const scriptElement = this.document.createElement('script');
   scriptElement.src = 'https://....js';
   scriptElement.type = 'text/javascript';
   const headElements = this.document.getElementsByTagName('head');
   headElements[0].appendChild(scriptElement);
}

then you can call this method inside a component constructor, or your app module constructor :

app.module.ts:

export class AppModule {
  constructor() {
    this.loadScript();
  }

  loadScript() {
    ...
  }
}


more details with [this tutorial][1].


  [1]: http://www.lukasjakob.com/how-to-dynamically-load-external-scripts-in-angular/
Thierry Falvo
  • 5,892
  • 2
  • 21
  • 39
  • Would you be able to link me to further tutorials to understand a little more. I am not really a programmer but would love to be able to fix this issue where we are loading other scripts before our main and lagging the load of our page. – Lucas Gomez Mar 23 '20 at 08:13
  • 1
    I've updated my answer. You'll find a lot of other resources by searching "external script angular" . – Thierry Falvo Mar 23 '20 at 08:30
  • Thanks a lot! Is it possible to add defer to these scripts? – Lucas Gomez Mar 23 '20 at 20:37