【问题标题】:Explanation of the use of async defer for the Google Maps APIGoogle Maps API 使用 async defer 的说明
【发布时间】:2018-08-19 22:09:21
【问题描述】:

我试图了解https://developers.google.com/maps/documentation/javascript/tutorial 的代码sn-p 中<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

【问题讨论】:

  • 您的第一个脚本没有实例化地图——它定义了一个函数,一旦加载,Google 的脚本就会调用该函数。请参阅 Google 脚本 URL 中的callback=initMap 参数。

标签: javascript deferred-loading


【解决方案1】:

要将 Charlie 的评论转换为答案,Google Maps API 的 src 末尾的 &amp;callback=initMap 可确保在 Google Maps 完成加载后调用 initMap 函数。

【讨论】:

    猜你喜欢
    • 2013-01-09
    • 2016-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    • 2012-12-20
    • 2013-06-26
    • 2016-11-05
    相关资源
    最近更新 更多