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


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

$.getScript("CAGScript.js", function () {
    try {
    } catch(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?


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:

  url: url,
  dataType: 'script',
  success: success

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

  url: url,
  dataType: 'script',
  success: success,
  async: false
Related Question