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:
- 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 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.