Skip to content

Instantly share code, notes, and snippets.

@thexmanxyz
Last active March 30, 2020 14:04
Show Gist options
  • Save thexmanxyz/006aa14b7281e8a46ff4fc4bf2d1815b to your computer and use it in GitHub Desktop.
Save thexmanxyz/006aa14b7281e8a46ff4fc4bf2d1815b to your computer and use it in GitHub Desktop.
Asynchronous Google Maps loading, jQuery plugin: https://github.com/thexmanxyz/Async-Google-Maps
// to make this code working for your Google Maps <iframe> please change the src-attribute to data-src and add the class g-maps
// e.g. <iframe class="g-maps" data-src="{your-google-maps-url}" width="100%" height="400" frameborder="0" style="border:0" allowfullscreen></iframe>
// you probably also want to prevent container resizing, please use this CSS with your height value: .g-maps { min-height: 400px; }
var loadGMapAsync = function() {
// determine if container is in viewport
// you might pass an offset in pixel - a negative offset will trigger loading earlier, a postive value later
// credits @ https://stackoverflow.com/a/33979503/2379196
var isInViewport = function($container, offset) {
var containerTop = $container.offset().top;
var containerBottom = containerTop + $container.outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return containerBottom > viewportTop && containerTop + offset < viewportBottom;
};
var loadGMaps = function() {
// only load Google Maps if the src attribute is not set, a data-src attribute exist and container is in viewport
// this prevents double loading of the same Google Maps iframe
if (!$(this).attr('src') && $(this).attr('data-src') && isInViewport($(this), 0)) {
$(this).attr('src', $(this).attr('data-src'));
}
};
$('.g-maps').each(loadGMaps); // load all maps async
};
// only react on resize and scroll events you might need to debounce if necessary
$(window).on('resize scroll', loadGMapAsync);
// do one initial check because map might be in viewport
loadGMapAsync();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment