Skip to content

Instantly share code, notes, and snippets.

@Rod911
Last active September 15, 2023 06:03
Show Gist options
  • Save Rod911/1badebcbf351f43e8ee3e96042e12a42 to your computer and use it in GitHub Desktop.
Save Rod911/1badebcbf351f43e8ee3e96042e12a42 to your computer and use it in GitHub Desktop.
Lazy load iframes using IntersectionObserver

Lazy load iframes using IntersectionObserver

Iframes with loading="lazy" attribute will still send network requests when they have not entered the browser's viewport. Setting the src attribute only after they reach the viewport ensures the page loads quickly (Noticeable when embedding Youtube or Google Maps iframes).

<div class="embed-container">
<iframe data-lazy-load="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d124422.27581607456!2d77.53719718240434!3d12.959298924679347!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x3bae1670c9b44e6d%3A0xf8dfc3e8517e4fe0!2sBengaluru%2C%20Karnataka!5e0!3m2!1sen!2sin!4v1694757340031!5m2!1sen!2sin" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade" frameborder=0></iframe>
</div>
// Function to lazy load iframes
function lazyLoadIframes() {
const lazyIframes = document.querySelectorAll('[data-lazy-load]');
const observerOptions = {
root: null,
rootMargin: '0px',
threshold: 0.1,
};
const iframeObserver = new IntersectionObserver((entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const iframe = entry.target;
const iframeSrc = iframe.getAttribute('data-lazy-load');
// Set the src attribute to load the iframe
iframe.setAttribute('src', iframeSrc);
// Stop observing the iframe once it's loaded
observer.unobserve(iframe);
}
});
}, observerOptions);
// Start observing each iframe
lazyIframes.forEach((iframe) => {
iframeObserver.observe(iframe);
});
}
// Call the function to start lazy loading iframes
lazyLoadIframes();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment