eddyP23
eddyP23

Reputation: 6825

Angular application - where to put script tags

I am trying to integrate payments in my angular application and both providers (Paypal and Adyen) give you a js file hosted on their webpage that they recommend putting in the HTML. Something like this:

<script src="https://www.paypalobjects.com/api/checkout.js"></script>

There is no npm package that I could import as any other piece of js.

So from what I understand, you are not allowed to put <script> in angular components themselves, but I am not a fan of putting it in the index.html, as it will `be loaded on the app load, increasing the load time of the application, whereas it is needed only in a few components related to payments and could be loaded much later. Thanks.

Any ideas?

Upvotes: 2

Views: 1808

Answers (1)

Gregor Ojstersek
Gregor Ojstersek

Reputation: 1379

If you are using Angular CLI, you have an .angular-cli.json file where you can insert your custom scripts. You can insert your custom scripts to the "scripts" property that takes an array of relative paths to the files. For example you can do:

"scripts": [
    "js/someScript.js",
    "js/anotherScript.js"
]

You also do not have to worry about the minification of those files. Webpack does that for you.

If you wish to dynamically load some external js files without loading everything in a bundle you can do it like this in your component.ts. AS specified in this answer.

loadScripts() {
    const dynamicScripts = [
   'https://platform.twitter.com/widgets.js',
   '../../../assets/js/dummyjs.min.js'
  ];
  for (let i = 0; i < dynamicScripts.length; i++) {
    const node = document.createElement('script');
    node.src = dynamicScripts[i];
    node.type = 'text/javascript';
    node.async = false;
    node.charset = 'utf-8';
    document.getElementsByTagName('head')[0].appendChild(node);
  }
}

And in the constructor.

constructor() {
  this.loadScripts();
}

But as far as the SPA way to go, there is no problem loading everything in the begining, since after the initial load, they wouldn't get loaded anymore.

Upvotes: 3

Related Questions