Javascript – Is the callback on jQuery’s getScript() unreliable or am I doing something wrong

javascriptjquery

I'm using the following bit of script to load another one:

$.getScript("CAGScript.js", function () {
    try {
        CAGinit();
    } catch(err) {
        console.log(err);
    }
});

The idea is that $.getScript loads the script, then executes the callback when it's done. CAGInit() is a function that lives in CAGScript.js.

The problem is that roughly half the time, CAGInit() doesn't fire (in any browser). Logging to the Firebug console reports that it's not defined. The rest of the time it works perfectly.

Does anyone have any ideas what I'm doing wrong?

Thanks.

Best Solution

I noticed the same issue with FF 3.6.

A solution is to load the script synchronously.

As mentioned in jQuery's documentation, getScript is shorthand for:

$.ajax({
  url: url,
  dataType: 'script',
  success: success
});

Everything works fine if I use the following instead of getScript:

$.ajax({
  url: url,
  dataType: 'script',
  success: success,
  async: false
});
Related Question