在JavaScript中如何等待动态注入的脚本在开始使用之前加载? [英] In JavaScript how to wait for dynamically injected scripts are loaded before start using them?
本文介绍了在JavaScript中如何等待动态注入的脚本在开始使用之前加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
不使用任何外部库如何在使用之前等待脚本加载。
Without using any external library how can I wait for a script to load before using it.
在我的情况下我正在加载脚本使用:
In my case I'm loading the scripts using:
(function (w,d,t,s,e,r) {
e = d.createElement(o);
r = d.getElementsByTagName(o)[0];
e.async = 1;
e.src = g;
r.parentNode.insertBefore(e, r)
})(window, document, 'script', '//mydomain.com/path/to/script.js');
以后:
// then later I want to use some code form the script:
var obj = new classFromTheInjectedScript();
是否有等待脚本加载然后开始使用它?
Is there away to wait for the script to load and then start using it?
注意:我有一种方法可以在脚本中触发我希望
加载然后收听的事件你可以在下面看到它,但这是一个好主意吗?
Note: I have a way that I can trigger an event within the script I want to load and then listen to it as you can see below, but is this a good idea?
(function(w,d){
document.addEventListener('scriptLoadedCustomEvent',onScriptReady);
function onScriptReady(){
// what I need to do goes here!
}
})(window,document);
推荐答案
您可以使用 onload
和 onerror
< script>
标记的事件。很好的例子这里。
You can use onload
and onerror
events for <script>
tag. Good example here.
这篇关于在JavaScript中如何等待动态注入的脚本在开始使用之前加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文