Question: As from the jquery api page
<http://api.jquery.com/jQuery.getScript/>

> 
> Success Callback
> ----------------
> 
> 
> The callback is fired once the script has been loaded but not necessarily executed.
> 
> 
> 
> ```
> $.getScript("test.js", function() {
>     foo();
> });
> 
> ```
> 
> 

if the `foo()` function depend on test.js, it cannot be execute successfully. 

I saw similar thing with google map api but in that case you can specify the callback function in the ajax script url. But in general is there an obvious way to wait until the ajax script executed to do the callback?

Answer: 
`$.getScript(...)` + `setInterval(...)` worked for me:
======================================================

```
$.getScript('https://www.google.com/recaptcha/api.js')
  .done(function() {
    var setIntervalID = setInterval(function() {
      if (window.grecaptcha) {
        clearInterval(setIntervalID);
        console.log(window.grecaptcha);
        letsWorkWithWindowDotGreptcha();
      };
    }, 300);
  });

  function letsWorkWithWindowDotGreptcha() {
    // window.greptcha is available here....
  }

```

Once the `variable` we are looking for is defined (in my case `window.grecaptcha`, i can call a `closure function` which can be `abstracted out`. 

Good Luck...
I was facing the same issue today and came up with a solution based on promises and a interval timer:

```
$.getScript("test.js", function() {
    var $def = $.Deferred();
    if (typeof foo === 'undefined') { // "foo" isn't available
        var attempts = 0;
        // create an interval
        // that will check each 100ms if the "foo" function
        // was loaded
        var interval = setInterval(function() {
            if (typeof foo !== 'undefined') { // loaded
                window.clearInterval(interval);
                $def.resolve();
            }
            // after X unsuccessfull attempts, abort the operation
            else if (attempts >= 100) {
                window.clearInterval(interval);
                $def.reject('Something went wrong');
            }

            attempts++;
        }, 100);
    }
    else { // "foo" is available
        $def.resolve();
    }
    return $def.promise();
}).then(function() {
    // at this point "foo()" is definitely available.
}).fail(function() {
    // deal with the failure
});

```

The ideia is that you load a given script that will expose some variable (the `foo` function in your question example) that still doesn't exist, so after the script is loaded by `getScript` you check if this variable exists, if not you create an interval that will continuously check if the variable is available, and only when this condition is satisfied you resolve the promise.