4

The PageSpeed Insights shows me that I to remove the render-blocking for my google maps js. It is added the in cms content and this is the code:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=myipcode">// <![CDATA[

// ]]></script>
<script type="text/javascript">// <![CDATA[
function initialize() {
  var myLatlng = new google.maps.LatLng(mycoord1, mycoord2);
  var mapOptions = {
    zoom: 17,
    center: myLatlng
  }
  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: 'My Title'
  });
}

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

 

If I add the async="async" to the the maps is not loaded but the message from the pagespeed disappers. What should I do ?

6

Try the following

<div id="map"></div>

<script type="text/javascript">
function initializeMap() {
  var myLatlng = new google.maps.LatLng(mycoord1, mycoord2);
  var mapOptions = {
    zoom: 17,
    center: myLatlng
  }
  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: 'My Title'
  });
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=myipcode&callback=initializeMap"
        async defer></script>

It's vital to place the external script tag AFTER the rest so it has something to callback to. Also, using async means you have to add a callback method to let it initialize.

I would advise against initialize as a method name as it is pretty generic and might be used elsewhere

Not the answer you're looking for? Browse other questions tagged or ask your own question.