Skip to content

Instantly share code, notes, and snippets.

@diegosomar
Created March 18, 2020 14:16
Show Gist options
  • Save diegosomar/bf272ffc10127c3808d564a7cd6fdc70 to your computer and use it in GitHub Desktop.
Save diegosomar/bf272ffc10127c3808d564a7cd6fdc70 to your computer and use it in GitHub Desktop.
/**
* Manage lazy load for entire site
* @link https://developers.google.com/web/fundamentals/performance/lazy-loading-guidance/images-and-video
*/
document.addEventListener("DOMContentLoaded", function() {
let lazyImages = [].slice.call(document.querySelectorAll("img.lazyload"));
let lazyBackgrounds = [].slice.call(document.querySelectorAll(".lazy-background"));
let lazyIframes = [].slice.call(document.querySelectorAll('iframe[data-src]'));
if ("IntersectionObserver" in window) {
// Lazy load <img> tag
let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
let lazyImage = entry.target;
lazyImage.src = lazyImage.dataset.src;
lazyImage.srcset = lazyImage.dataset.srcset;
lazyImage.classList.remove("lazy");
lazyImageObserver.unobserve(lazyImage);
}
});
});
lazyImages.forEach(function(lazyImage) {
lazyImageObserver.observe(lazyImage);
});
// Lazy load background images
let lazyBackgroundObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
let element = entry.target;
let image_url = element.dataset.src;
if ( image_url != null && image_url != '' ){
element.style.backgroundImage = `url(${image_url})`;
}
lazyBackgroundObserver.unobserve(entry.target);
}
});
});
lazyBackgrounds.forEach(function(lazyBackground) {
lazyBackgroundObserver.observe(lazyBackground);
});
// Lazy load iframes
let lazyIframeObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
let lazyIframe = entry.target;
lazyIframe.src = lazyIframe.dataset.src;
lazyIframeObserver.unobserve(lazyIframe);
}
});
});
lazyIframes.forEach(function(lazyIframe) {
lazyIframeObserver.observe(lazyIframe);
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment