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

1 Answer 1

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/
Sign up to request clarification or add additional context in comments.

3 Comments

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.
I've updated my answer. You'll find a lot of other resources by searching "external script angular" .
Thanks a lot! Is it possible to add defer to these scripts?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.