Hi,
Is it possible to lazysize a Google Maps?
Thanks,
Roberto.
Yes this should be possible if you use the JS API events. Here's some demo code as to how that might look:
$('.googleMap').on('lazybeforeunveil', function(e){
$(e.target).initializeGoogleMap();
});
That code doesn't seem to work. Is anyone actually managed to lazysize a Google Map?
<div class="lazyload" data-script="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap"></div>
<script>
var initMap = function () {
var mapEl = document.getElementById('js-map');
if (mapEl && typeof google !== "undefined") {
var myLatlng = new google.maps.LatLng(LAT, LONG);
var map;
try {
map = new google.maps.Map(mapEl, {
center: myLatlng,
zoom: 14
});
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'title',
});
marker.setVisible(true);
} catch (e) {
console.log('Error:' + e.message);
}
}
};
document.addEventListener('lazybeforeunveil', function (e) {
var src = e.target.getAttribute('data-script');
if (src) {
var script = document.createElement('script');
script.async = true;
script.src = src;
document.head.appendChild(script);
}
});
</script>
Note that script should be right after lazyloaded div.
Since Google Maps API require credit card even for free usage I switched to iframe embed and I can easily lazyload them.
Most helpful comment
Note that script should be right after lazyloaded div.