有没有办法确定外部脚本何时已经加载并执行?我知道我们可以使用 onload
事件来确定它何时被加载,如下所示:
<script src=script.js async></script>
<script>
document.getElementsByTagName('script')[0].onload = function(){...}
</script>
那加载和执行呢?
有没有办法确定外部脚本何时已经加载并执行?我知道我们可以使用 onload
事件来确定它何时被加载,如下所示:
<script src=script.js async></script>
<script>
document.getElementsByTagName('script')[0].onload = function(){...}
</script>
那加载和执行呢?
var deferreds = [];
var jsFiles = ['https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-debug.js', 'https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.js'];
$.each(jsFiles, function(idx, url) {
deferreds.push(jQuery.ajax({
type: "GET",
url: url,
dataType: "script",
cache: true
}));
});
deferreds.push($.Deferred(function(deferred) { $(deferred.resolve); }));
$.when.apply(this, deferreds).done(function() {
console.log("KnockoutJS & MomentJs is loaded", ko, moment);
});
var wait = function (condFunc, readyFunc, checkInterval) {
var checkFunc = function () {
if (condFunc()) {
readyFunc();
}
else {
setTimeout(checkFunc, checkInterval);
}
};
checkFunc();
};
wait(
function() { return new Date().getSeconds() % 10 == 0 },
function() { console.log("this will be called when time is 0, 10, 20, 30, etc seconds", new Date()); },
10);
var isNamespaceDefined = function(moduleName) {
var fields = moduleName.split('.'), cur = window;
for(var i=0; i<fields.length; i++){
if(typeof cur[fields[i]] === "undefined") return false;
cur = cur[fields[i]];
}
return true;
};
isNamespaceDefined("my.module.function")
结合setTimeout来检查加载情况:var doWhenReady = function(){
if(isNamespaceDefined("my.function")){
// redefining the function;
var _myFunction = my.function;
my.function = function(){
// do things Before the call
_myFunction.apply(null, arguments);
// do things After the call
};
}
else{
setTimeout(doWhenReady , 100);
}
}