Lazy Loading Images and Video Web Fundamentals Google Developers PDF
Lazy Loading Images and Video Web Fundamentals Google Developers PDF
ALL PRODUCTS
Contents
#
What is lazy loading?
Why lazy load images or video instead of just
loading them?
Lazy loading images
Inline images
By Jeremy Wagner
Jeremy is a contributor to
WebFundamentals
Inline images
&'
<img class="lazy" src="placeholder-i
&'
document.addEventListener("DOMConten
var lazyImages = [].slice.call(doc
if ("IntersectionObserver" in wind
let lazyImageObserver = new Inte
entries.forEach(function(entry
if (entry.isIntersecting)
let lazyImage = entry.targ
lazyImage.src = lazyImage
lazyImage.srcset = lazyIma
lazyImage.classList.remove
lazyImageObserver.unobserv
}
});
});
lazyImages.forEach(function(lazy
lazyImageObserver.observe(lazy
});
} else {
// Possibly fall back to a more
}
});
&'
document.addEventListener("DOMConten
let lazyImages = [].slice.call(doc
let active = false;
setTimeout(function() {
lazyImages.forEach(function
if ((lazyImage.getBounding
lazyImage.src = lazyImag
lazyImage.srcset = lazyI
lazyImage.classList.remo
lazyImages = lazyImages
return image !== lazyI
});
if (lazyImages.length
document.removeEventLi
window.removeEventList
window.removeEventList
}
}
});
active = false;
}, 200);
}
};
document.addEventListener("scroll"
window.addEventListener("resize"
window.addEventListener("orientati
});
Images in CSS
&'
<div class="lazy-background">
<h1>Here's a hero heading to get y
<p>Here's hero copy to convince yo
<a href="/buy-a-thing">Buy a thing
</div>
.lazy-background { &'
background-image: url("hero-placeh
}
.lazy-background.visible {
background-image: url("hero.jpg"
}
&'
document.addEventListener("DOMConten
var lazyBackgrounds = [].slice.cal
if ("IntersectionObserver" in wind
let lazyBackgroundObserver = new
entries.forEach(function(entry
if (entry.isIntersecting)
entry.target.classList.add
lazyBackgroundObserver.uno
}
});
});
lazyBackgrounds.forEach(function
lazyBackgroundObserver.observe
});
}
});
&'
<video controls preload="none" poste
<source src="one-does-not-simply.w
<source src="one-does-not-simply.m
</video>
&'
<video autoplay muted loop playsinli
<source src="one-does-not-simply.w
<source src="one-does-not-simply.m
</video>
&'
<video autoplay muted loop playsinli
<source data-src="one-does-not-sim
<source data-src="one-does-not-sim
</video>
&'
document.addEventListener("DOMConten
var lazyVideos = [].slice.call(doc
if ("IntersectionObserver" in wind
var lazyVideoObserver = new Inte
entries.forEach(function(video
if (video.isIntersecting)
for (var source in video
var videoSource = video
if (typeof videoSource
videoSource.src = vide
}
}