javascript - 未加载谷歌地图回调?

标签 javascript google-maps google-maps-api-3

Google 提供此脚本来初始化 Google map :

<script async defer src="https://maps.googleapis.com/maps/api/js key=YOUR_API_KEY&callback=initMap">

我想重点说的部分是:

callback=initMap

由于脚本是使用async defer 加载的并且是非阻塞的,所以当调用 initMap 回调时实际发生了什么,而保存此函数的文件是还没有加载?

假设此函数被放入外部文件并在 Google map 脚本之后加载。这可能来自另一台服务器,当回调尝试调用该函数时,该服务器可能未及时加载。

它是否尝试调用该函数并失败并且只执行一次?

最佳答案

Since the script is being loaded with async defer and is non-blocking , what actually happens when the initMap callback is being called while the file that holds this function is not yet loaded?

您将得到类似于 initMap is not defined 的异常.

解决方案是使用 defer 以正确的顺序加载 JavaScript 文件仅限属性:

<script defer src="https://example.com/initMap.js"></script>
<script defer src="https://maps.googleapis.com/maps/api/js key=YOUR_API_KEY&callback=initMap">

defer属性并行加载脚本但保留执行顺序(在健全的浏览器中)。

另一种解决方案是嵌入 initMap函数在 HTML 页面中,并将 <script defer><script async defer>之后。

关于javascript - 未加载谷歌地图回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43363557/

相关文章:

android - 使用 Google Maps Android API v2 的当前 map 缩放级别的半径大小(以十进制度表示)

javascript - 将 Google Maps V3 限制为 1 个标记

android - 在谷歌地图上显示 ListView 项目点击位置

javascript - 某个点是否包含在比 map 边界稍大一点的范围内?

javascript - 为什么 KML 未加载到 Google map 中?

javascript - 在钛 TableView 行中选择特定元素

javascript - 使用 jQuery 更改图像源

javascript - gmaps.js |添加新标记时删除旧标记

javascript - 为什么每次刷新logo我的页面都会自动上去?

javascript - Paypal智能按钮结账无需发货