如何在继续之前立即加载(动态添加)脚本文件? [英] How to load the script file immediately (dynamically added) before continue?
本文介绍了如何在继续之前立即加载(动态添加)脚本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已将以下脚本文件加载到了角度的home.component.ts文件中
I have loaded script file like below code in angular home.component.ts file
export class HomeComponent {
constructor() {
this.loadDynmicallyScript();
}
public loadDynmicallyScript() {
var script = document.createElement('script');
script.src = "../node_modules/xxxxxx/i18n/xx.min.js";
script.async =false;
document.head.appendChild(script);
}
但是在创建组件之后及以后加载此文件.因此,在这种情况下,它不使用此文件.附加到文档中后,我想加载此文件.如何实现呢?
But this file gets loaded after components created and later. So, in this case, it makes no use of this file. I want to load this file once I appended in documents. How to achieve this?
推荐答案
您可以返回对连锁呼叫的承诺
You can return a promise to chain calls
export class HomeComponent {
constructor() {
this.loadDynmicallyScript()
.then(() => {
this.doSomethingWhenScriptIsLoaded();
});
}
public loadDynmicallyScript():Promise {
var script = document.createElement('script');
script.src = "../node_modules/xxxxxx/i18n/xx.min.js";
script.async =false;
document.head.appendChild(script);
return Promise((resolve, reject) => {
script.onload = resolve;
});
}
或仅将函数传递给onLoad
,以便在加载脚本时被调用
or just pass a function to the onLoad
to be called when the script was loaded
export class HomeComponent {
constructor() {
this.loadDynmicallyScript()
}
public loadDynmicallyScript():Promise {
var script = document.createElement('script');
script.src = "../node_modules/xxxxxx/i18n/xx.min.js";
script.async =false;
document.head.appendChild(script);
script.onload = () => this.doSomethingWhenScriptIsLoaded();
}
这篇关于如何在继续之前立即加载(动态添加)脚本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文