延迟加载谷歌地图 api v3 jQuery 回调

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4102579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:40:34  来源:igfitidea点击:

lazy load google maps api v3 jQuery callback

jquerygoogle-mapscallbacklazy-loading

提问by astropanic

I do lazy loading of the google maps api v3 javascript

我懒加载谷歌地图 api v3 javascript

The documentation says about putting as a callback parameter in the url the name of the function, which will be executed, when the script has loaded.

该文档说明了将函数的名称作为回调参数放入 url 中,该函数将在脚本加载时执行。

 $(document).ready(function(){
   var s = document.createElement("script");
   s.type = "text/javascript";
   s.src  = "http://maps.google.com/maps/api/js?v=3&sensor=true&callback=gmap_draw";
   $("head").append(s);
 });

So I must define the gmap_draw() function.

所以我必须定义 gmap_draw() 函数。

When I enclose this function in the domready block, it is not visible.

当我将此函数包含在 domready 块中时,它是不可见的。

Any workarounds of this issue ? (except putting the function out of the domready block)

此问题的任何解决方法?(除了把函数放在 domready 块之外)

回答by Jonathan

Another option is to use Google Loader:

另一种选择是使用Google Loader

$.getScript('https://www.google.com/jsapi', function()
{
    google.load('maps', '3', { other_params: 'sensor=false', callback: function()
    {
        // Callback code here
    }});
});

回答by Chris Laplante

Because the callback must be global, you could make one by accessing windowfrom within the ready handler.

因为回调必须是全局的,您可以通过window从就绪处理程序中访问来创建一个。

$(document).ready(function(){
   var s = document.createElement("script");
   s.type = "text/javascript";
   s.src  = "http://maps.google.com/maps/api/js?v=3&sensor=true&callback=gmap_draw";
   window.gmap_draw = function(){
       alert ("Callback code here");
   };
   $("head").append(s);  
});