Is there anyway to determine when an external script has loaded AND executed? I know that we can determine when it has been loaded using the onload
event like this:
<script src=script.js async></script>
<script>
document.getElementsByTagName('script')[0].onload = function(){...}
</script>
But what about loaded and executed?
Here is a method to load multiple JS scripts using jQuery deferreds and $.ajax method. Message on console will be printed when BOTH JS files are loaded & executed
Demo http://jsbin.com/qumojobawe/2/edit?html,js,output
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);
});
If script loads additional components and does not initialize immediately you can use following wait() method which will wait until certain condition is met by rechecking it on specified interval
var wait = function (condFunc, readyFunc, checkInterval) {
var checkFunc = function () {
if (condFunc()) {
readyFunc();
}
else {
setTimeout(checkFunc, checkInterval);
}
};
checkFunc();
};
For example, following code will check when current time number of seconds ends with zero every 10 milliseconds and executes function when condition is true:
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);
Demo http://jsbin.com/fayenigixo/1/edit
If you are asking about script, that you can modify, then you can write a callback function in external script. You can read more about it here: http://www.w3schools.com/jquery/jquery_callback.asp
If you are asking about external script, that you can not modify, then you should read API documentation, if it exists. For example, here you can find a YouTube's API docs: https://developers.google.com/youtube/js_api_reference#Functions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With