3

We use $.getScript(url, callback) all over the place. In troubleshooting very occasional undefined errors, i noticed this from the jQuery documentation:

"The callback is fired once the script has been loaded but not necessarily executed."

Can anyone suggest a generic way to guarantee the callback is called after the script is executed?

I know I could poll for a var that gets defined in the script, but i'm hoping for a more elegant solution (because i'd have to make this change in hundreds of spots for hundreds of different variables)... like a callback I've missed from the documentation.

thanks in advance!

Orlando
  • 147
  • 1
  • 9

1 Answers1

0

You should be able to do this quite easily using getJSON.

http://api.jquery.com/jQuery.getJSON/

Something similar to this should do the trick:

$.getJSON( url , 
    function(data) {
       //Do something with data here 
       alert(data);
});

EDIT: The answer from the link below that I find most interesting is this one:

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

It seems that disabling the asynchronous part of ajax will execute the script first, then the callback afterwords, instead of doing them synchronously.

Tricky12
  • 6,752
  • 1
  • 27
  • 35
  • I believe both getJSON and getScript are shorthand for $.ajax calls, with the difference being the datatype. getJSON sets dataType="json" and getScript sets dataType= "script". Since in our case we're most definitely loading scripts, this doesn't seem to work (as a sanity check i tried). – Orlando Aug 07 '13 at 21:09
  • You are correct, I completely misread your problem. For some reason I thought your problem was with the data you were running in your scripts. I think that this link may be helpful to you. The first answer involves polling as you mentioned, but perhaps some of the other suggestions will achieve what you're looking for: http://stackoverflow.com/questions/1130921/is-the-callback-on-jquerys-getscript-unreliable-or-am-i-doing-something-wrong – Tricky12 Aug 08 '13 at 12:32