I'm trying to make sure the Google map is the last thing that loads on the page and doesn't affect the performance of the page negatively.
When the defer attribute is placed after ...sensor=false", the map does not appear. What's the best way to use the defer attribute with Google maps? Is this even possible?
<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>[email protected]</li><li>[email protected]</li><li>[email protected]</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>
When you use defer you must use the asynchronous version of the API:
<script defer
src="http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize">
</script>
The issue:
when you use defer
the script will be loaded when the document is closed- the content has been loaded. Furthermore external deffered scripts will be parsed after inline defferred scripts.
This has two side-effects related to your implementation:
you can't use the synchronous version of the API, because it makes use of document.write
, which can't be used after the document has been closed
the call :
google.maps.event.addDomListener(window, 'load', initialize);
...comes at a point where the Maps-API isn't loaded yet, google
is undefined, initialize will never be executed.