繁体   English   中英

找不到谷歌地图回调函数

[英]google maps callback function is not found

我依次加载了以下文件:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=try_to_initialize"></script>
<%= javascript_include_tag "application" %>

其次引用的application.js.erb具有以下代码行:

function try_to_initialize() {
    initialize_google_maps();

    if (typeof initial_data !== 'undefined') {
        google_maps_draw_data(initial_data, false);
    }
}

该函数在全局空间中定义。 它不在任何类型的事件处理程序或本地范围中。

我检查了网络选项卡,以确保文件按顺序加载:

js?v=3.exp&sensor=false&callback=try_to_initialize  GET 200 script  (index):30  (from cache)    6 ms    
application-3332227d778ac1e4b9e987588145ff49.js GET 200 script  (index):31  (from cache)    0 ms    

一切看起来都很好。 不幸的是,在控制台中,我收到以下错误:

js?v=3.exp&sensor=false&callback=try_to_initialize:95 Uncaught InvalidValueError: try_to_initialize is not a function

我知道错误提示。 我只是不知道为什么会这样。 为什么找不到功能?

问题

函数定义的顺序在相对较小的应用程序中很重要。 如果您先放置Google JS加载程序,然后再放置init ,则脚本将阻止其他资源加载,直到完全加载为止。

测试1(无异步属性)

以下示例将从Google引擎抛出错误,将其作为带有消息的对象:

初始化不是函数

 function init(){ console.log('API loaded'); } 
 <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&callback=init"></script> 

更改<script>的顺序将解决此问题,因为将定义init ,然后浏览器获取Google库。

 <script> function init(){ console.log('API loaded'); } </script> <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&callback=init"></script> 

测试2(异步)

我在<script>使用了async属性,以确保它不会阻止其余资源的加载。

 function init(){ console.log('API loaded'); } 
 <!-- the following script will act as block because of async attribute --> <script async src="https://maps.googleapis.com/maps/api/js?v=3.exp&callback=init"></script> 

暂无
暂无

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

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