[英]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
,則腳本將阻止其他資源加載,直到完全加載為止。
以下示例將從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>
我在<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.