我试图确保 Google 地图是页面上最后加载的内容,并且不会对页面的性能产生负面影响。

当 defer 属性放在 ...sensor=false" 之后时,地图不会出现。在 Google 地图上使用 defer 属性的最佳方式是什么?这可能吗?

 <div id="map-canvas"></div>
        <script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false" defer></script>
        <script defer>
            function initialize() {
                var mapOptions = {
                    center: new google.maps.LatLng(37.7599446, -122.4212681),
                    zoom: 12,
                    panControl: false,
                    disableDefaultUI: true,
                    scrollwheel: false,
                    mapTypeControl: false,
                    mapTypeControlOptions: {
                        style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
                    },
                    panControlOptions: {
                        position: google.maps.ControlPosition.LEFT_CENTER
                    },
                    zoomControl: true,
                    zoomControlOptions: {
                        position: google.maps.ControlPosition.LEFT_CENTER
                    },
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };

                var map = new google.maps.Map(document.getElementById("map-canvas"),
                    mapOptions);

                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(37.7599446, -122.4212681),
                    map: map,
                    title: '805 Valencia St. San Francisco, CA'
                });
                var contentString = '<div id="map-content">' +
                    '<div id="siteNotice">' +
                    '</div>' +
                    '<h1 id="firstHeading" class="firstHeading">805 Valencia St.<br>San Francisco, CA</h1>' +
                    '<div id="bodyContent">' +
                    '' +
                    '<ul class="email-list"><li>info@yourbetty.com</li><li>support@yourbetty.com</li><li>press@yourbetty.com</li></ul>' +
                    '</div>' +
                    '</div>';

                var infowindow = new google.maps.InfoWindow({
                    content: contentString,
                    maxWidth: 330
                });

                google.maps.event.addListener(marker, 'click', function () {
                    infowindow.open(map, marker);
                });

            }

            google.maps.event.addDomListener(window, 'load', initialize);
        </script>
有帮助吗?

解决方案

当您使用 defer 时,您必须使用 API 的异步版本:

<script defer 
  src="http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize">
</script>

问题:
当你使用 defer 关闭文档时将加载脚本 - 内容已加载。此外,外部延迟脚本将在内联延迟脚本之后进行解析。

这有两个与您的实施相关的副作用:

  1. 您不能使用 API 的同步版本,因为它使用 document.write ,文档关闭后无法使用

  2. 电话:

    google.maps.event.addDomListener(window, 'load', initialize); 
    

    ...在 Maps-API 尚未加载时出现, google 未定义,初始化永远不会被执行。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top