我使用这种标准方法来动态加载脚本。
import {Injectable} from "@angular/core";
import {ScriptStore} from "./script.store";
declare var document: any;
@Injectable()
export class ScriptService {
private scripts: any = {};
constructor() {
ScriptStore.forEach((script: any) => {
this.scripts[script.name] = {
loaded: false,
src: script.src
};
});
}
load(...scripts: string[]) {
var promises: any[] = [];
scripts.forEach((script) => promises.push(this.loadScript(script)));
return Promise.all(promises);
}
loadScript(name: string) {
return new Promise((resolve, reject) => {
//resolve if already loaded
if (this.scripts[name].loaded) {
resolve({script: name, loaded: true, status: 'Already Loaded'});
}
else {
//load script
let script = document.createElement('script');
script.type = 'text/javascript';
script.src = this.scripts[name].src;
if (script.readyState) { //IE
script.onreadystatechange = () => {
if (script.readyState === "loaded" || script.readyState === "complete") {
script.onreadystatechange = null;
this.scripts[name].loaded = true;
resolve({script: name, loaded: true, status: 'Loaded'});
}
};
} else { //Others
script.onload = () => {
this.scripts[name].loaded = true;
resolve({script: name, loaded: true, status: 'Loaded'});
};
}
script.onerror = (error: any) => resolve({script: name, loaded: false, status: 'Loaded'});
document.getElementsByTagName('head')[0].appendChild(script);
}
});
}
}
问题在于它仅适用于外部路径。使用此设置,我无法加载bootstrap-datepicker.js,但在使用'https://cdnjs.cloudflare.com/ ...'时将其加载。有人可以帮忙吗?我应该通过路由使该脚本可用吗?
interface Scripts {
name: string;
src: string;
}
export const ScriptStore: Scripts[] = [
{ name: "paypal", src: "https://www.paypalobjects.com/api/checkout.min.js" },
{
name: "datepicker",
src: "../../../../node_modules/bootstrap-datepicker/js/bootstrap-datepicker.js"
//"https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"
},
{
name: "datepickerEs",
src:
"https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/locales/bootstrap-datepicker.es.min.js"
}
];
答案 0 :(得分:2)
否,您应该通过资产来使用该脚本。
将您的node_modules模块中的脚本进行编译和 bundled ,以单个脚本(通常为name
)结束。如果您只有一个脚本文件,则不能在其上使用延迟加载。
为此,请从节点模块中提取脚本,将其放入资产文件夹中,然后使用该脚本位置进行延迟加载。