gpt4 book ai didi

javascript - 谷歌地图 JS v3 : detect load failures

转载 作者:行者123 更新时间:2023-12-02 17:32:35 25 4
gpt4 key购买 nike

我正在使用 this technique 加载 Google map 代码大致如下(使用 jQuery):

            $.ajax({
url: "//maps.googleapis.com/maps/api/js?client=" + GOOGLE_MAPS_CLIENT_ID + "&v=" + GOOGLE_MAPS_API_VERSION + "&sensor=false&libraries=geometry&callback=googleMapsOnLoad",
crossdomain: true,
dataType: 'script'
});

其中 window.googleMapsOnLoad 是我成功加载的处理程序。

一般情况下它工作得很好,但有时对于我的一些用户来说,据我所知,它只是无法正确加载。是否有某种方法可以附加错误回调,如果加载以某种方式失败,该回调将触发?

最佳答案

没有真正的方法来检查,因为有时加载某些资源(处理器、连接速度等)可能需要很长时间。处理这个问题的一种方法是在有限的时间内设置适当的超时(以下建议为 5 秒)。

function checkGMapsLoad() {
if( !window.googleMapsOnLoad ) {
//Error, Google Maps hasn't loaded yet. Reload page?
//Stuff to perform here
}
}

window.setTimeout( checkGMapsLoad, 5000 );

编辑:由于您使用 jQuery 进行调用,jQuery.ajax() 有一个可以使用的参数 error以防回调失败。

            $.ajax({
url: "//maps.googleapis.com/maps/api/js?client=" + GOOGLE_MAPS_CLIENT_ID + "&v=" + GOOGLE_MAPS_API_VERSION + "&sensor=false&libraries=geometry&callback=googleMapsOnLoad",
crossdomain: true,
dataType: 'script',
timeout: 5000, // <------ Optional
error: checkGMapsLoad // <------
});

jQuery.ajax() Documentation

关于javascript - 谷歌地图 JS v3 : detect load failures,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22923106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com