简体   繁体   中英

How to call external javascript function in angular 5?

I have downloaded a theme from this link. I have to define script and CSS in index.html file.

index.html (body section)

<body>
  <app-root></app-root>
  <script type="text/javascript" src="./assets/js/main.85741bff.js"></script>
  <script type="text/javascript" src="./assets/js/common.js"></script>
</body>

I have defind my function in common.js and call it from main.85741bff.js file.

common.js (function)

document.addEventListener("DOMContentLoaded", function (event) {
     masonryBuild();
     navbarToggleSidebar();
     navActivePage();
});

The issue is that I am able to call the function while page reloads but can't call the function while content load.

Can anyone help me to resolve this issue? Any help would be appreciated.

You can use javascript in the Angular application.

Step 1. Create demo.js file in assets/javascript folder.

export function test1(){
    console.log('Calling test 1 function');
}

Step 2. Create demo.d.ts file in assets/javascript folder.

export declare function test1();

Step 3. Use it in your component

import { test1 } from '../assets/javascript/demo'; 
 @Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor() {
    console.log(test1());
  }
}

Note: js and .d.ts file name should be same

You need to change the order in which you load your JavaSciprt files. Try loading common.js before main......js . Your script tries to access a function from a file that hasn't been loaded yet. Try just switching those two lines of code:

<body>
  <app-root></app-root>
  <script type="text/javascript" src="./assets/js/common.js"></script>
  <script type="text/javascript" src="./assets/js/main.85741bff.js">/script>
</body>

In Angular4, 5 project folder, there is .angular-cli.json file.

In file, you will see

"apps": [
  {
    "scripts": []
  }
]

push your external js file path in the array.

You can call these methods by window object-

document.addEventListener("DOMContentLoaded", function (event) {
      window['navbarToggleSidebar']();
      window['navActivePage']();
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM