I am curious about how lazy loading images, images that will be loaded when scrolled to them, works.
Any hint?
Native lazy loading API Lazy loading is built on top of the Intersection Observer API, which is a browser API that provides a way of detecting or knowing when an element called a target, a parent element, or becomes available or visible inside the browsers viewport, as the case may be.
Using browser-level lazy-loading #This attribute can be added to <img> elements, and also to <iframe> elements. A value of lazy tells the browser to load the image immediately if it is in the viewport, and to fetch other images when the user scrolls near them. Note <iframe loading="lazy"> is currently non-standard.
If you want to test the execution of lazy loading, I can recommend that you clear your browser's cache and try reloading. In Chrome's Developer Console (F12), you can tweak the speeds and simulate modem speeds. Hit F12 -> Network tab -> Change the "No throttling" dropdown . Choose a slower speed to experiment.
Lazy loading is the practice of delaying load or initialization of resources or objects until they're actually needed to improve performance and save system resources.
Lots of plugin recommendations here, and depending on your use case those may be valuable to you.
If you can't be bothered to write this short snippet of code below, or you need callbacks already built out then you can use this plugin I built which is based on this exact answer and only 0.5kb when minified. My plugin, Simply Lazy, can even work with IE if you simply add a polyfill.
At the end of the day if you just need to lazy load some images then it's as simple as:
<img data-src="your-image-path-here" class="lazyload" />
And:
let observer = new IntersectionObserver((entries, observer) => {
entries.forEach(function (entry) {
if (entry.intersectionRatio > 0 || entry.isIntersecting) {
const image = entry.target;
observer.unobserve(image);
if (image.hasAttribute('src')) {
// Image has been loaded already
return;
}
// Image has not been loaded so load it
const sourceUrl = image.getAttribute('data-src');
image.setAttribute('src', sourceUrl);
image.onload = () => {
// Do stuff
}
// Removing the observer
observer.unobserve(image);
}
});
});
document.querySelectorAll('.lazyload').forEach((el) => {
observer.observe(el);
});
Using the Intersection Observer API makes this all very simple. You can also use it within the shadowRoot
and it works fine there as well.
I've also found this article helpful to understand what is going on here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With