简体   繁体   中英

Fail fast when loading google maps asynchronously

I have an web app where some pages use the google maps API.

I'm using the async load with callback like explained in the documentation : https://developers.google.com/maps/documentation/javascript/tutorial?csw=1#asynch
It works great when the network connection is ok. However, if for whatever reason, the browser fails to download the google maps script, it will hang for about 10 second before an unrecoverable connection an error. That network error stops the script execution and I cannot continue with my app process.

I want to recover from that error to continue the process of my webapp just with a info message telling the user that Google Maps isn't availaible for the moment.

I tried the following but it obviously doens't work because of cross domain xmlhttprequest access :

$.get("https://maps.googleapis.com/maps/api/js?key=.......",function(){
     var googlemapsscript = document.createElement('script');
     googlemapsscript.type = 'text/javascript';
     googlemapsscript.src = 'https://maps.googleapis.com/maps/api/js?key=........&sensor=false&callback=successLoadGoogleMaps';
     document.body.appendChild(googlemapsscript);
}).fail(function(){
    errorLoadGoogleMaps();
});

When it has trouble accessing Google Maps API, the jquery $.get fails, thus running immediately errorLoadGoogleMaps() . However when it can access the API it throws the cross domain error.

I'm looking for the following behavior :
- Try to download Google Maps API
- Fail fast if it isn't availaible
- If available, continue with the success callback

Currently as a bad workaround I'm using a callback written in the script element : googlemapsscript.onerror="errorLoadGoogleMaps()"

However it doesn't fail fast at all, the browser try to download the script for about 10 seconds before throwing the error and executing the callback.

How to fail immediately when trying to download an unavailable script (in particular Google Maps API here) ?

您可能要使用jQuery.getScript() ,它应该处理很多错误,并为您提供浏览器支持。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM