I am in the process of developing an Angular 5 application and I have encountered a challenge while trying to integrate a widget into one of the components.
Following the guidance provided in this particular question, I attempted to add the widget as instructed. However, I have noticed that it occasionally fails to load, without any clear reason as to why this is happening.
The script responsible for loading the widget looks like this:
<script src="https://example.com/widget/js/widgetLoader.js"
type="text/javascript"
charset="utf-8"
data-id="xxxxx"
data-target="WidgetPlaceHolder"
data-displaymeta="off"
data-css="https://example.com/widget/css/temp/widget.css"
data-type="widget-type"
data-lv="en"
data-apikey="xxx-xxx">
</script>
In order to incorporate the widget into my component, I have utilized the following code snippet:
public loadScript() {
let widgetScripts = 'https://example.com/widget/js/widgetLoader.js';
let node = document.createElement('script');
node.src = widgetScripts ;
node.type = 'text/javascript';
node.async = false;
node.charset = 'utf-8';
node.setAttribute('data-id', this.information.id);
node.setAttribute('data-target', 'WidgetPlaceHolder');
node.setAttribute('data-displaymeta', 'off');
node.setAttribute('data-css', 'https://example.com/widget/css/temp/widget.css');
node.setAttribute('data-type', 'widget-type');
node.setAttribute('data-lv', 'en');
node.setAttribute('data-apikey', 'xxx-xxx');
document.getElementsByTagName('head')[0].appendChild(node);
}
Subsequently, I have initialized the script loading process within my component's lifecycle hook like so:
loadWidget: Promise<any>;
ngOnInit() {
this.loadWidget = new Promise((resolve) => {
this.loadScript();
resolve(true);
});
}
My inquiry pertains to whether there exists a more suitable approach for incorporating scripts into Angular applications. Is there an Angular-specific API or library designed to facilitate this task?