在不使用任何外部库的情况下,如何在使用之前等待脚本加载.
在我的情况下,我正在使用以下命令加载脚本:
(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');
Run Code Online (Sandbox Code Playgroud)
然后:
// then later I want to use some code form the script:
var obj = new classFromTheInjectedScript();
Run Code Online (Sandbox Code Playgroud)
有没有等待脚本加载然后开始使用它?
注意:我有一种方法可以在我想要加载的脚本中触发事件,然后听到它,如下所示,但这是一个好主意吗?
(function(w,d){
document.addEventListener('scriptLoadedCustomEvent',onScriptReady);
function onScriptReady(){
// what I need to do goes here!
}
})(window,document);
Run Code Online (Sandbox Code Playgroud)
小智 7
你应该可以做这样的事情!
var script = document.createElement('script');
script.src = url; //source
var callback = function (){
// do stuff after loaded
}
script.onload = callback;
document.head.appendChild(script); //inject where you need it to be
Run Code Online (Sandbox Code Playgroud)