2

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!

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.