【发布时间】:2017-08-17 14:37:42
【问题描述】:
我的 jsp 页面中有两个 Javascript 加载,第一个加载 google maps API,第二个加载调用 google.maps.OverlayView 的 JS 文件。由于 googleapis 的异步加载,对 google 的引用显然失败了,但是即使我删除了 async 和 defer,问题仍然存在。有人可以推荐一种解决方法吗?
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?key=mykey>">
</script>
<!-- This file uses Google APIs -->
<script src="<c:url value="/resources/js/InfoBox.js"/>">
</script>
</head>
<body>
<script>
//This is the callback function after Google Maps API loads
function initMap() {
var container=document.getElementById("map");
var anantapur = {lat: 14.68, lng: 77.6};
var mapOptions = {
styles: mapStyle,
zoom: 6,
minZoom: 5,
maxZoom: 10,
center: anantapur
};
var newMap = new google.maps.Map(container, mapOptions);
}
</script>
</body>
</html>
上述内容将导致 InfoBox.js 中使用 google maps 对象的行出现错误“google not defined”。
一般来说,如果我只能异步加载 Google APIs 脚本,如何包含其他使用 Google API 对象的脚本文件?
【问题讨论】:
-
你不能在第一次加载后在回调中加载第二个文件吗?
-
请提供一个minimal reproducible example 来证明这个问题。
-
谢谢。我正是这样做的——我在回调中动态加载了第二个文件并且它起作用了。我是 javascript 新手,不熟悉动态加载,并在 stackflow 中找到了如何做到这一点。
标签: javascript google-maps asynchronous