I have been using this piece of script to load external .js files to the document:
$.ajax({
url: dir + '/' + module + '.js',
dataType: 'script',
async: false,
success: function() {
modules[module].init();
},
error: function(xhr) {
alert('Error loading module "' + module + '"');
}
});
But when I switch to jQuery 1.5.1 (instead of 1.4.2 I was using before) it stops working. It loads the file but not as a success – file contents gets passed as errors xhr.responseText
Can you use the ‘complete’ event from $.ajax() instead of the ‘success’ event?
If you need to dynamically load a javascript source file, you can append the [script] tag to the [head] tag:
The only problem with that, is you must prevent the script from getting loaded more than once.
I like to have an if() condition which tests for the presence of a function that I know is defined in the dynamically loaded javascript file. I use underscore.js and _.isFunction() to test for this ( http://documentcloud.github.com/underscore/#isFunction ). Only load the javascript src file if the test function isn’t defined: