I have encountered some challenges while attempting to import external JS and CSS files into my Angular 5 application.
Below is the code snippet that I have tried so far:
Component.ts :
ngOnInit() {
this.loadScript(); // also attempted with constructor
}
loadScript () {
const head = document.getElementsByTagName('head')[0];
const link = document.createElement('link');
const s = this.document.createElement('script');
s.type = 'text/javascript';
s.src = 'https://**/assets/js/patterns/name.min.js';
link.id = 'pattern';
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'https://**/assets/js/patterns/name.min.css';
link.media = 'all';
head.appendChild(link);
const __this = this;
s.onload = function () { __this.afterScriptAdded(); };
this.elementRef.nativeElement.appendChild(s);
}
I also tried loading from an scss file by adding this line:
@import url("https://**/assets/js/patterns/name.min.css");
While I can see the files in the network tab, there seems to be a delay in their loading. This results in my functions rendering without these dependencies, only for them to load later when not needed anymore.
The solution currently works only upon reloading, switching between components freezes the first time and only displays properly after a page refresh, along with the dynamic scripts connected.
I've come across several questions on this matter but haven't found a working solution yet:
- Dynamically load external javascript file from Angular component
- How to load external scripts dynamically in Angular?
If anyone has faced a similar situation before, any assistance would be greatly appreciated :)