I often need to load other javascript files via ajax, so at the beginning I used the standard function jQuery provides for script loading:
$.getScript('script_name.js',callback_function());
But this didn’t work out, since $.getScript is asynchronous (the jQuery API for $.ajax says ‘async’ is set to true by default; topic is discussed in the comments of the API for $.getScript: http://api.jquery.com/jQuery.getScript/). So I wrote this function, as provided by someone in the comments of the API page linked above:
load:function(script,callback){
jQuery.ajax({
async:false,
type:'GET',
url:script,
data:null,
success:callback,
dataType:'script'
});
},
This seemed to work well, so I went on, but I recently noticed, that this only works for scripts in the same directory, eg. calling myObj.load(‘test.js’) works well, but calling myObj.load(‘test/test.js’) doesn’t work at all.
It feels like I’m missing something obvious, but I didn’t manage to find the problem. Any idea?
Update: See the comment stream below, it’s nothing to do with jQuery, it’s a file permissions problem on the server.
Original answer:
Do you get any errors from the browser? For instance, in Chrome or Safari, if you open the Dev Tools and look at the Console tab, does it show errors? Or in Firefox, install Firebug and check in Firebug’s console. Or in IE, use the free version of VS.Net… Something should be complaining to you about something.
You can also get more information from your code itself by supplying an
errorfunction rather than assuming success:Update: You’ve said you see
textStatus= ‘error’ anderrorThrown= undefined. Very strange. Does the same script work if you move it so it’s not on a subpath? I wonder if the subpath is a red herring, and the real problem is a syntax error in the script.Off-topic: Does it really have to be synchronous? You can’t just poll for a symbol to appear? It’s just that synchronous ajax requests really trash the user experience. In many browsers, not just your own page but all pages lock up during the request.
Here’s what I mean by polling: Suppose I wanted to load jQuery asynchronously from JavaScript:
Usage: