jquery 仅在文件准备好时获得 maps.google.com

jquery get maps.google.com only when document ready

里面 <head></head> 放置 <script src="http://maps.google.com/maps/api/js?sensor=true"></script>

有时打开页面需要很长时间。当页面加载时,请参阅 Read maps.gstatic.com。删除后 <script src="http://maps.google.com/maps/api/js?sensor=true"></script> 页面加载速度很快。

因此决定仅在加载文档的其他部分时才开始加载<script src="http://maps.google.com/maps/api/js?sensor=true"></script>

尝试过

$(document).ready(function() {
$.getScript("http://maps.google.com/maps/api/js?sensor=true");
});

但是报错uncaught exception: Google Maps API is required. Please register the following JavaScript library http://maps.google.com/maps/api/js?sensor=true.

也尝试了这个 https://developers.google.com/maps/documentation/javascript/examples/map-simple-async 外部文档就绪

function loadScript() {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'http://maps.google.com/maps/api/js?sensor=true';
  document.body.appendChild(script);
}
window.onload = loadScript;

遇到同样的错误

只有在加载其他内容后才能加载 google 地图脚本需要更改什么?

您在脚本中省略了所需的回调参数-url。

此回调参数应为全局函数的名称。

在调用此函数之前,您可能无法在某处访问 google.maps-properties/methods,因此您应该访问此函数,例如创建地图或请求服务。将所有与 google.maps 相关的脚本封装到此函数中。

当您加载需要映射的库时-API(例如 MarkerClusterer),您还必须异步加载这些库(在回调中)和 运行 基于此库的脚本,当库已加载。

根据错误消息,我猜你想使用 GMaps-library(这当然需要地图 -API)。

地图异步加载示例-API 和 GMaps:

//script-loader
function loadScript(url,callback){
    var script = document.createElement('script');
    script.setAttribute('type','text/javascript');
    if(typeof callback==='function'){
      script.addEventListener('load',callback,false);
    }
    script.setAttribute('src',url);
    document.body.appendChild(script);
}
  
//callback-function for load of maps-API
function init(){
    alert(['init',
           '---------',
           'google.maps->'+typeof google.maps,
           'GMaps->'+typeof window.GMaps 
          ].join('\n'));
    
    //callback-function for load of GMaps-library
    init2=function(){
       alert(['init2',
           '---------',
           'google.maps->'+typeof google.maps,
           'GMaps->'+typeof window.GMaps 
          ].join('\n'));
      new GMaps({
        div: '#map',
        lat: 0,
        lng: 0,
        zoom:1
      });
    }
    //load GMaps
    loadScript('https://cdnjs.cloudflare.com/ajax/libs/gmaps.js/0.4.12/gmaps.min.js',init2);
}

//load the maps-API asynchronously  
window.addEventListener(
 'load',
 function(){
  loadScript('https://maps.google.com/maps/api/js?v=3&callback=init')
 },
 false);
      html ,
      body ,
      #map{ 
        height: 100%; margin: 0; padding: 0;
      }
<div id="map"></div>

为此有些挣扎...具有讽刺意味的是,找到了一种更简单的方法来完成工作并准备好文档。他们的关键是同步加载它。

 <div id="map"></div>
 <script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&key='Your KEY'>&callback=InitMap&language=en">
 </script>