I want to Lazy Load Google Maps to get a better pageload-speed for SEO. My javascript works, but it still tries to load the map multiple times. How can i get it to load once? I found other scripts but i want to use as less code as possible.
My script:
google = false;
$(window).scroll(function() {
var hT = $('#google-map').offset().top,
hH = $('#google-map').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > (hT+hH-wH)){
if (!google) $.getScript( 'https://maps.googleapis.com/maps/api/js?key={key}', function( google, textStatus, jqxhr ) {
initialize();
});
}
});
Console log:
js?key={key}&_=1591085205888:140 You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
dj @ js?key={key}&_=1591085205888:140
js?key={key}&_=1591085205890:140 You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
dj @ js?key={key}&_=1591085205890:140
js?key={key}&_=1591085205891:140 You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
dj @ js?key={key}&_=1591085205891:140 You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
Thanks in advance!
Peter
2
Answers
This works, only fires once. Thanks Sprep && Musefan
I think you are running the script over and over? Add a google = true after the if statement?
Revised as per suggestion from musefan
You can also make it like