jQuery's getScript function doesn't seem to support an error callback function. I can't use the global ajax error handling code here, a local error function would be ideal.
Documentation that the callback gets data/textStatus seems incorrect - the callback gets neither.
Any suggestions on how I detect that a call to getScript failed (server not available, for instance)?
EDIT: Just looked at source, and it seems like the callback is only invoked on success, with data always set to null and textStatus not defined (since it's a success-only callback, I presume). The documentation is very incorrect for this function.
As of jQuery 1.5 you can append a .fail to your call to getScript.
$.getScript('foo.js', function(){
//script loaded and parsed
}).fail(function(){
if(arguments[0].readyState==0){
//script failed to load
}else{
//script loaded but failed to parse
alert(arguments[2].toString());
}
})
http://api.jquery.com/jQuery.getScript/#handling-errors
For cross domain script tags, the success event fires but the error event does not; no matter what syntax you use. You can try this approach:
handle = window.setTimeout
window.clearTimeout(handle)
Sample code:
var timeoutId; // timeout id is a global variable
timeoutId = window.setTimeout(function() {
alert("Error");
}, 5000);
$.getScript("http://other-domain.com/script.js", function(){
window.clearTimeout(timeoutId);
});
The global JQuery Ajax-ErrorHandler will work!
Prior to the $.getScript-Call setup the Error Handler to cach the error.
$(document).ajaxError(function(e, xhr, settings, exception) {
alert('error in: ' + settings.url + ' \n'+'error:\n' + exception );
});
As described in the JQuery manual: http://api.jquery.com/ajaxError/.
jquery.ajax has a alternative way to handle error
jQuery.ajax({
type: "GET",
url: 'http://www.example.com/script_test.js',
dataType: "script",
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log('error ', errorThrown);
},
success:function(){
console.log('success');
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With