S
S
Sergey Burduzha2020-03-11 13:01:14
JavaScript
Sergey Burduzha, 2020-03-11 13:01:14

How to load google map after full page load?

Good afternoon.
I want to speed up the loading of the site on pagespeed.
With a map, the site loads 70%, without - 97.

And so, there are divs
<div class="map" id="js-map"></div>

Before the body, I registered scripts

<script>
  // Initialize and add the map
  function initMap() {
    // The location of Uluru
    var mapCenter = {lat: 45.9590269, lng: 12.3180639};
    // The map, centered at Uluru
    var map = new google.maps.Map(
      document.getElementById('js-map'), {zoom: 15, center: mapCenter});
    // The marker, positioned at Uluru
    var marker = new google.maps.Marker({position: mapCenter, map: map});
  }
</script>
<!--Load the API from the specified URL
* The async attribute allows the browser to render the page while the API loads
* The key parameter will contain your own API key (which is not needed for this tutorial)
* The callback parameter executes the initMap() function
-->
<script id="js-map-load" async defer
        src="">
</script>


And in main.js I wrote a script for jquery.
let mapOffsetTop = $('#js-map').offset().top;
  let scriptGoogleMapApi = $('#js-map-load');

  $(window).on('scroll', function () {
    if($(this).scrollTop() > mapOffsetTop) {
      if(scriptGoogleMapApi.attr('src') === ''){
        scriptGoogleMapApi.attr('src', 'https://maps.googleapis.com/maps/api/js?key=KEY&callback=initMap')
      }
    }
  });


Only when scrolling, the path to the google map is written in the src tag, but the map does not work.
Something I didn't learn.

Thanks in advance for the hint.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor Stasyuk, 2020-03-11
@serii81

Because the map is initialized before you change the src. Make it so that it is initialized after the entire DOM load, or immediately after setting the src

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question