Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the callback on jQuery's getScript() unreliable or am I doing something wrong?

Tags:

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.

like image 286
Olly Hodgson Avatar asked Jul 15 '09 11:07

Olly Hodgson


2 Answers

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 }); 
like image 191
Fabrice Avatar answered Oct 04 '22 16:10

Fabrice


Just wanted to offer some insight I have on this issue. The callback won't fire if there is an error in the code you are loading and (at least on Chrome with jQuery 1.7.1) the error will be swallowed. I discovered that I had a stray curly brace from autocomplete in the code I was loading and the callback function didn't fire. Intermittent behavior here could be caused by changing the loaded code between tests.

like image 35
gibbitz Avatar answered Oct 04 '22 14:10

gibbitz