1

I'm currently using the Google Maps API script:

function loadScript() {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&key=KEY&sensor=false&callback=callback";
    document.body.appendChild(script);
}

I already have a fallback using the response status in the callback but how to create a fallback in case say the API is unreachable for any reason, i.e. when the script above doesn't load?

Alternatively, is this overkill and should one assume the API will always be there for you?

greener
  • 4,989
  • 13
  • 52
  • 93

1 Answers1

1

You need to define a timeout to determine if the script has or hasn't loaded. For example, if the script takes 10 seconds to load, that could be acceptable, but if it's taking more than 10, you could consider it "not loaded".

var apiLoaded = false;
function loadScript() { }
function callback() { 
    apiLoaded = true;
}
setTimeout(function() {
    if (apiLoaded === false) {
        // your backup logic here
    }
, 10000);
Brad M
  • 7,857
  • 1
  • 23
  • 40
  • Thanks. This got me toward the right answer which I found here: http://stackoverflow.com/questions/9014473/how-can-i-timeout-a-google-maps-geocoder-via-javascript – greener Feb 26 '13 at 22:26