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/