Is it possible in $.getScript() to create a condition where if the first js script fails to load - for whatever reason - then run the second js? Like a backup?
Any way to make this work with jQuery 1.2 and/or 1.4?
Thanks a lot!
As long as you're using jQuery 1.5 or greater then $.getScript() returns a Promise so you can attach a function to both success and failure. They show an example in their documentation where they attach to fail like so:
$.getScript("ajax/test.js")
.done(function(script, textStatus) {
console.log( textStatus );
})
.fail(function(jqxhr, settings, exception) {
$( "div.log" ).text( "Triggered ajaxError handler." );
});
There's no reason why you couldn't do another $.getScript() within the function that .fail() calls.
Did you read the docs for this? It's quite clear, as of jquery 1.5, you can use .fail()
$.getScript("ajax/test.js")
.done(function(script, textStatus) {
console.log( textStatus );
})
.fail(function(jqxhr, settings, exception) {
$( "div.log" ).text( "Triggered ajaxError handler." );
});
earlier than that, you use the global ajax error:
$( "div.log" ).ajaxError(function(e, jqxhr, settings, exception) {
if (settings.dataType=='script') {
$(this).text( "Triggered ajaxError handler." );
}
});
or more pratically, just don't rely on getscript, and use the .ajax fn:
$.ajax({
url: url,
dataType: "script",
success: success,
error:function(){
//load the second script here
}
});