Core_dumped
Core_dumped

Reputation: 1611

is there a way to detect when external js has loaded and executed?

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 onloadevent like this:

<script src=script.js async></script>
<script>
document.getElementsByTagName('script')[0].onload = function(){...}
</script>

But what about loaded and executed?

Upvotes: 6

Views: 2340

Answers (3)

Hacketo
Hacketo

Reputation: 4997

You can check if a namespace is "loaded" with a method like this :

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;
};

usage : isNamespaceDefined("my.module.function")

Combined with a setTimeout to check the loading:

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);
    }
}

A simple solution, but may be added with some time check and error callback

Upvotes: 0

Maksym Kozlenko
Maksym Kozlenko

Reputation: 10363

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

Upvotes: 2

Maxim Mazurok
Maxim Mazurok

Reputation: 4162

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

Upvotes: 1

Related Questions