In my Angular 5 application, I am faced with the challenge of loading a JavaScript script file dynamically after my component view has been fully loaded.
This script is closely related to my component template, requiring the view to be loaded before it can properly execute.
I have attempted the following approach:
export class MyComponent implements AfterViewInit{
title = 'app';
ngAfterViewInit() {
this.loadScript('http://www.some-library.com/library.js');
// OR THIS
this.loadScript('../assets/js/my-library.js');
}
}
public loadScript(url: string) {
const body = <HTMLDivElement> document.body;
const script = document.createElement('script');
script.innerHTML = '';
script.src = url;
script.async = false;
script.defer = true;
body.appendChild(script);
}
}
However, the issue persists as the JavaScript file is still loaded before the component HTML file, resulting in the script not functioning as intended.
(Even though it appears in the body, it does not work as expected)
The primary goal is to ensure that my JavaScript file is loaded after my component is fully loaded.
Any suggestions on how to achieve this?