异步加载谷歌地图 [英] Loading google maps asynchronously
问题描述
我试图加载我的谷歌地图异步,它的工作原理,但它加载地图两次。如果我删除 box.onload = initialize;
,则会停止该问题,但信息框不会显示...如何修复我的代码,以便仅加载映射一次并显示信息框。
I am trying to load my google map asynchronously and it works but it is loading the map in twice. If I remove "box.onload = initialize;
" this stops that problem but then the infobox doesn't show...how do I fix my code so it only loads the map once AND shows the infobox.
function loadScript() {
var map = document.createElement('script');
map.type = 'text/javascript';
map.src = 'https://maps.googleapis.com/maps/api/js?key=key_goes_here&sensor=false&callback=initialize';
document.body.appendChild(map);
map.onload = function() {
var box = document.createElement('script');
box.type = 'text/javascript';
box.src = 'https://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox_packed.js';
document.body.appendChild(box);
box.onload = initialize;
};
}
window.onload = loadScript;
推荐答案
c $ c>初始化两次。
The map appears twice because you're calling initialize
twice.
在解决这个问题之前,让我们简化一下代码。永远不要让自己重复那样的代码块;而是将它变成一个通用函数。
Before fixing that, let's simplify your code a bit. Never let yourself repeat blocks of code like that; instead make it into a common function.
另外,请勿从googlecode.com加载infobox.js; Google代码不是CDN。加载您自己的副本。
Also, don't load infobox.js from googlecode.com; Google Code is not a CDN. Load your own copy.
所以,代码可能如下所示:
So, the code may look like this:
function addScript( url, callback ) {
var script = document.createElement( 'script' );
if( callback ) script.onload = callback;
script.type = 'text/javascript';
script.src = url;
document.body.appendChild( script );
}
function loadMapsAPI() {
addScript( 'https://maps.googleapis.com/maps/api/js?key=key_goes_here&sensor=false&callback=mapsApiReady' );
}
function mapsApiReady() {
addScript( 'infobox.js', initialize );
}
window.onload = loadMapsAPI;
这篇关于异步加载谷歌地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!