Skip to content

How to lazy-load Google Maps

Given this HTML:

<div id="google-map"></div>

We can easily use IntersectionObserver to run code only when certain module is visible on screen, not only Google Maps.

In this case, we wait until the map is actually visible before initializing it.

const map = document.getElementById('google-map');
  if (map) {
    if ('IntersectionObserver' in window) {
      const observer = new IntersectionObserver((entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            initMap(map);
          }
        });
      });
      observer.observe(map);
    }
    else {
      initMap(map);
    }
  }

This optimizes rendering, mainly on small screens, where that map is buried at the bottom of the page.