Answer the question
In order to leave comments, you need to log in
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>
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')
}
}
});
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question