Lucas Gomez
Lucas Gomez

Reputation: 145

Adding scripts after Angular 8 compiled scripts (main.js, polyfill.js, etc)

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

Upvotes: 1

Views: 739

Answers (1)

Thierry Falvo
Thierry Falvo

Reputation: 6300

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/

Upvotes: 1

Related Questions