简体   繁体   English

异步加载Google地图时快速失败

[英]Fail fast when loading google maps asynchronously

I have an web app where some pages use the google maps API. 我有一个网络应用程序,其中某些页面使用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 我正在使用异步加载和回调,如文档中所述: 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. 但是,如果由于某种原因浏览器无法下载google maps脚本,它将在无法恢复的连接出现错误之前挂起大约10秒钟。 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. 我想从该错误中恢复以继续执行我的webapp程序,并仅显示一条信息消息,告知用户目前暂时无法使用Google Maps。

I tried the following but it obviously doens't work because of cross domain xmlhttprequest access : 我尝试了以下操作,但是由于跨域xmlhttprequest访问,它显然不起作用:

$.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() . 如果无法访问Google Maps API,则jquery $ .get失败,因此立即运行errorLoadGoogleMaps() However when it can access the API it throws the cross domain error. 但是,当它可以访问API时,它将引发跨域错误。

I'm looking for the following behavior : 我正在寻找以下行为:
- Try to download Google Maps API -尝试下载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()" 目前,作为一种不好的解决方法,我正在使用在script元素中编写的回调: 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. 但是,它并不会很快失败,浏览器会在抛出错误并执行回调之前尝试下载脚本约10秒钟。

How to fail immediately when trying to download an unavailable script (in particular Google Maps API here) ? 尝试下载不可用的脚本(尤其是此处的Google Maps API)时如何立即失败?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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