簡體   English   中英

Google Maps API 使用 async defer 的說明

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM