[英]Explanation of the use of async defer for the Google Maps API
我試圖了解https://developers.google.com/maps/documentation/javascript/tutorial代碼片段中<script>
元素的加載:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
async defer></script>
</body>
</html>
據推測, google.maps.Map
對象是在后一個script
定義的。 但是,該腳本具有async defer
屬性,根據https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script意味着它將在文檔被解析后異步執行. 但由於這是以后的第一個script
,如何能第一script
實例化一個Map
的定義已經加載之前?
要將 Charlie 的評論轉換為答案,Google Maps API src
末尾的&callback=initMap
確保在 Google Maps 加載完成后調用initMap
函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.