External JS Files Are Not Loading Correctly In Angular

I found that sometimes, external js will not work or load correctly in an Angular solution, especially while designing the theme. Specifically, I found that some external js having functions are not working or loading because which the theme was not functioning as per expectation. In my case, I was using the Admin LTE bootstrap theme, likewise, I faced a similar issue with some other themes as well.

After doing some research, I found a solution that we can load through a typescript file.

In my case, I loaded the js file through a common component as depicted below:

  1. export class FooterComponent implements OnInit {  
  2.   
  3.   constructor() { }  
  4.   
  5.   ngOnInit() {  
  6.     this.loadJsFile("assets/adminlte/dist/js/demo.js");  
  7.   }  
  8.   public loadJsFile(url) {  
  9.     let node = document.createElement('script');  
  10.     node.src = url;  
  11.     node.type = 'text/javascript';  
  12.     document.getElementsByTagName('head')[0].appendChild(node);  
  13.   }  
  14. }  

Description

Above, I created a function to load the js file in the head of the DOM and initiated that function in ngOnInit().

Alternatively, we can load the file in the module/component level as well.