从Angular组件动态加载外部javascript文件 [英] Dynamically load external javascript file from Angular component
问题描述
我正在使用Angular 4和CLI创建Angular应用程序.我正在尝试将SkyScanner搜索小部件添加到我的组件之一中.
I am creating an Angular application using Angular 4 and the CLI. I am trying to add the SkyScanner search widget into one of my components.
部分实现需要添加新的外部脚本:
Part of the implementation requires the addition of a new external script:
<script src="https://widgets.skyscanner.net/widget-server/js/loader.js" async></script>
我不确定引用此文件的正确方法.如果将脚本添加到index.html文件中,则除非执行整页刷新,否则不会加载小部件.我假设脚本试图在加载时操纵DOM,并且脚本运行时元素不存在.
I am not sure of the correct way to reference this file. If I add the script into my index.html file, the widget doesn't load unless a full page refresh is performed. I assume the script tries to manipulate the DOM on load and the elements don't exist when the script runs.
仅当加载包含Skyscanner小部件的组件时,加载脚本的正确方法是什么?
What is the correct way to load the script only when the component containing the Skyscanner widget is loaded?
推荐答案
尝试在组件加载时加载外部JavaScript,如下所示:
Try to load external JavaScript on component load as below :
loadAPI: Promise<any>;
constructor() {
this.loadAPI = new Promise((resolve) => {
this.loadScript();
resolve(true);
});
}
public loadScript() {
var isFound = false;
var scripts = document.getElementsByTagName("script")
for (var i = 0; i < scripts.length; ++i) {
if (scripts[i].getAttribute('src') != null && scripts[i].getAttribute('src').includes("loader")) {
isFound = true;
}
}
if (!isFound) {
var dynamicScripts = ["https://widgets.skyscanner.net/widget-server/js/loader.js"];
for (var i = 0; i < dynamicScripts.length; i++) {
let node = document.createElement('script');
node.src = dynamicScripts [i];
node.type = 'text/javascript';
node.async = false;
node.charset = 'utf-8';
document.getElementsByTagName('head')[0].appendChild(node);
}
}
}
这篇关于从Angular组件动态加载外部javascript文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!