Level 61
You do know that browsers support natively lazy loading for images?
<img loading="lazy" src="url"/>
I have gallery model , which will output all the iamge path ,so I make it with pagination , base on the view point each row displays 3 pics of image, I wanna tp implement lazt loading imag effect, which image at the bottom wont be load it until us scroll the page.
I use lozad js , and its not working , then I use some hand write js its working but only if I output image one by one in html structure
not working
<div class=" md:flex md:flex-wrap" id="lightgallery">
@forelse( $galleries as $gallery)
<div class="p-4 md:w-1/2 lg:w-1/3" >
<div data-src="{{ $gallery->path }}"
class="gallery-item dark:bg-myBlueGray-800 bg-white flex flex-col rounded-2xl shadow-2xl shadow-inner">
<!-- gallery picture -->
<a href="{{ $gallery->path }}" data-lg-size="1024-800">
<img
data-src="{{ $gallery->path }}"
class="lazy rounded-2xl"
src="{{ $gallery->path }}"
alt="gallery_image">
</a>
</div>
</div>
@empty
@endforelse
</div>
working html structure
@forelse( $galleries as $gallery)
<div class="p-4 " >
<div data-src="{{ $gallery->path }}"
class="gallery-item dark:bg-myBlueGray-800 bg-white flex flex-col rounded-2xl shadow-2xl shadow-inner">
<!-- gallery picture -->
<a href="{{ $gallery->path }}" data-lg-size="1024-800">
<img
data-src="{{ $gallery->path }}"
class="lazy rounded-2xl"
src="{{ $gallery->path }}"
alt="gallery_image">
</a>
</div>
</div>
@empty
<p>no gallery</p>
@endforelse
js that trigger lazy loading
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
var lazyloadImages;
if ("IntersectionObserver" in window) {
lazyloadImages = document.querySelectorAll(".lazy");
var imageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
var image = entry.target;
image.src = image.dataset.src;
image.classList.remove("lazy");
imageObserver.unobserve(image);
}
});
});
lazyloadImages.forEach(function(image) {
imageObserver.observe(image);
});
} else {
var lazyloadThrottleTimeout;
lazyloadImages = document.querySelectorAll(".lazy");
function lazyload () {
if(lazyloadThrottleTimeout) {
clearTimeout(lazyloadThrottleTimeout);
}
lazyloadThrottleTimeout = setTimeout(function() {
var scrollTop = window.pageYOffset;
lazyloadImages.forEach(function(img) {
if(img.offsetTop < (window.innerHeight + scrollTop)) {
img.src = img.dataset.src;
img.classList.remove('lazy');
}
});
if(lazyloadImages.length == 0) {
document.removeEventListener("scroll", lazyload);
window.removeEventListener("resize", lazyload);
window.removeEventListener("orientationChange", lazyload);
}
}, 20);
}
document.addEventListener("scroll", lazyload);
window.addEventListener("resize", lazyload);
window.addEventListener("orientationChange", lazyload);
}
})
</script>
am I not understand the js api correctly ? very confusing
Please or to participate in this conversation.