gpt4 book ai didi

javascript - jquery仅在文档准备好时获取maps.google.com

转载 作者:行者123 更新时间:2023-12-03 10:41:36 25 4
gpt4 key购买 nike

内部<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;

同样的错误

要更改什么才能仅在加载其他内容后加载谷歌地图脚本?

最佳答案

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

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

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

当您加载需要maps-API的库(例如MarkerClusterer)时,您还必须异步加载这些库(在回调中),并在加载库后运行基于该库的脚本。

根据错误消息,我猜您想使用 GMaps -library(当然需要 map API)。

map API 和 GMap 异步加载示例:

//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>

关于javascript - jquery仅在文档准备好时获取maps.google.com,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28757798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com