Angular: How to load external scripts across the application in all the components

Viewed 1191

Script tags:

<script src="https://www.test.com/dem0.js"></script>
<script src="https://www.test.com/dem01.js"></script>
<script src="https://www.test.com/dem02.js"></script>
<script src="https://www.test.com/dem03.js"></script>

Index.html:

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>Mobile</title>
  <base href="/">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="wsstitle" content="catalog">
  <meta name="wssmlc" content="/us/en/">

  <link rel="icon" type="image/png" href="favicon.ico" sizes="32x32">
  <link href="https://fonts.googleapis.com/css?family=Roboto:300,300i,400,400i,700,700i" rel="stylesheet">
</head>

<body>
  <app-root></app-root>
</body>

</html>

I've few external <script> tags and I want to make them available in whole app (should be able to load em whenever my view changed in the browser). If I include them in my index.html <head> tag it's only working for the first time when the app initially load but for my case I've to load them whenever the view changed. Including the scripts in the <body> tag will be a good practice ??

2 Answers

Add scripts reference path in angular-cli.json under

     "scripts": [
       "../src/assets/scripts/asn1.min.js"
      ],

To use it in component .ts file

declare var libraryName: any;

Here is some example that demostrate how integrate Jquery and angular loading jquery from external resource : https://stackblitz.com/edit/angular-e1nf7j

There are other code in the example to demostrate a little separation of angular code and Jquery. You can create a Wrapper class to write whatever you need with your library

The other part is to control your components lifecycle . and the Hooks will do the work executing your external code.

Note: You need to control the time it takes to load the external library in order to don't have null references, for that the setTimeout()

I hope it helps

Related