简体   繁体   English

找不到谷歌地图回调函数

[英]google maps callback function is not found

I have the following files loaded in sequence: 我依次加载了以下文件:

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

The application.js.erb referenced secondly has the following line of code: 其次引用的application.js.erb具有以下代码行:

function try_to_initialize() {
    initialize_google_maps();

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

The function is defined at the global space. 该函数在全局空间中定义。 It is not in any kind of event handler or local scope. 它不在任何类型的事件处理程序或本地范围中。

I checked the network tab to make sure the files are loaded in order: 我检查了网络选项卡,以确保文件按顺序加载:

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    

Everything looks fine. 一切看起来都很好。 Unfortunately, in the console I get the following error: 不幸的是,在控制台中,我收到以下错误:

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

I know what the error suggests. 我知道错误提示。 I just don't know why it is happening. 我只是不知道为什么会这样。 Why can't it find the function? 为什么找不到功能?

Problem 问题

The order of function definition matters in relatively small apps. 函数定义的顺序在相对较小的应用程序中很重要。 If you have Google JS loader put first, then init , the script will block other resources from loading until it is fully loaded. 如果您先放置Google JS加载程序,然后再放置init ,则脚本将阻止其他资源加载,直到完全加载为止。

Test 1 (without async attribute) 测试1(无异步属性)

The following example will throw an error from Google engine as an object with message: 以下示例将从Google引擎抛出错误,将其作为带有消息的对象:

init is not a function 初始化不是函数

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

Changing the order of <script> will fix the issue as init will be defined, and then browser fetches Google library. 更改<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> 

Test 2 (with async) 测试2(异步)

I have used async attribute in <script> to ensure it will not block the rest of resources from loading. 我在<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