Search code examples
javascriptjqueryamd

How to find if the chained asynchronous scripts has been loaded?


Here's the scenario. I am doing a $.getScript()function call to get a script in my javascript file. The script that I'm downloading from the $.getScript() tries to download some other scripts that it's dependent on. In my script I'm using done() to check if the script loaded completely or not. And if it did, then I try calling the function that's not on the script that I just loaded form $.getScript but the script that was loaded in it.

It's getting confusing so let me demonstrate with some code:-

//my script.js
$.getScript("http://myexternaljs.com/first.js").done(function(){
    doSecond(); //<- this resides in second.js which is being called in first.js below
}

//first.js
(function(){
    $.getScript("http://firstexternal.com/second.js");
}());

//second.js
function doSecond(){
    return console.log("hello world");
}

The problem here is second.js takes a little time to download so I keep getting doSecond() is undefined error on my call to doSecond() on done().

I could use a timeout and check if second.js loaded or not but is there a better way to do this?

I'm open to any AMD loaders or Promises answers as well.


Solution

  • You can also use $.ajaxSuccess:

    $(document).ajaxComplete(function(ev, jqXhr, options) {
      // You could be as specific as you need to here.
      if ( options.url.match('second.js') ) {
        doSecond();
      }
    });
    

    Alternatively, you could do this inside ajaxComplete:

    $(document).ajaxComplete(function(ev, jqXhr, options) {
      // You could simplify to 
      // doSecond && doSecond()
      // if you can trust that it will always be a function
      if ( doSecond && $.isFunction(doSecond) ) {
        doSecond();
      }
    });