External Js File is not working in Angular

I found that sometimes, some external js will not work or load correctly in angular solution specially while designing theme. Specifically, I have 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 Admin LTE bootstrap theme, likewise I faced similar issue with some another themes as well.

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

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

export class FooterComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    this.loadJsFile("assets/adminlte/dist/js/demo.js");
  }
  public loadJsFile(url) {
    let node = document.createElement('script');
    node.src = url;
    node.type = 'text/javascript';
    document.getElementsByTagName('head')[0].appendChild(node);
  }
}

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

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

Kind Regards,

By Rijwan Ansari

Research and Technology Lead | Software Architect | Full Stack .NET Expert | Tech Blogger | Community Speaker | Trainer | YouTuber. Follow me @ https://rijsat.com Md Rijwan Ansari is a high performing and technology consultant with 10 plus years of Software Development and Business Applications implementation using .NET Technologies, SharePoint, Power Platform, Data, AI, Azure and cognitive services. He is also a Microsoft Certified Trainer, C# Corner MVP, Microsoft Certified Data Analyst Associate, Microsoft Certified Azure Data Scientist Associate, CSM, CSPO, MCTS, MCP, with 15+ Microsoft Certifications. He is a research and technology lead in Tech One Global as well as leading Facebook community Cloud Experts Group and SharePoint User Group Nepal. He is a active contributor and speaker in c-sharpcorner.com community, C# Corner MVP and his rank at 20 among 3+ millions members. Additionally, he is knee to learn new technologies, write articles, love to contribute to the open-source community. Visit his blog RIJSAT.COM for extensive articles, courses, news, videos and issues resolution specially for developer and data engineer.

Leave a Reply

Your email address will not be published. Required fields are marked *