Yesterday, when I executed this code, everything functioned as expected. The observer
successfully loaded the images once they intersected the viewport:
<template>
<div id="gallery" class="gallery">
<div class="gallery-card">
<a href="#"><img src="../../images/1.jpg"></a>
<a href="#"><img src="../../images/ph.png" data-src="../../images/2.jpg"></a>
<a href="#"><img src="../../images/ph.png" data-src="../../images/3.jpg"></a>
<a href="#"><img src="../../images/ph.png" data-src="../../images/4.jpg"></a>
<a href="#"><img src="../../images/ph.png" data-src="../../images/5.jpg"></a>
<a href="#"><img src="../../images/ph.png" data-src="../../images/6.jpg"></a>
</div>
</div>
</template>
<script setup>
import {onMounted} from "vue";
onMounted(() => {
let config = {
rootMargin: '0px 0px 50px 0px',
threshold: 0
};
const observer = new IntersectionObserver(function(entries, self) {
console.log(entries)
entries.forEach(entry => {
if(entry.isIntersecting) {
const img = entry.target
img.src = img.dataset.src
self.unobserve(img);
}})
}, config);
const lazyImages = document.querySelectorAll('[data-src]');
lazyImages.forEach(img => {
console.log(img.src)
observer.observe(img);
});
})
</script>
However, today I noticed that the IntersectionObserver
loads all the images at once upon initial page load. To troubleshoot this issue, I utilized console.log()
, and strangely, the correct img
element is being passed to the observer
:
const lazyImages = document.querySelectorAll('[data-src]');
lazyImages.forEach(img => {
console.log(img.src)
observer.observe(img);
});
Output (x5, placeholder image):
http://localhost:3000/images/ph.png?3d03f427893c28791c9e0b8a347a277d
Nevertheless, the observer
seems to be receiving an initial entries
object with all isIntersecting
properties set to true
, leading to the loading of all images:
const observer = new IntersectionObserver(function (entries, self) {
console.log(entries)
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target
img.src = img.dataset.src
self.unobserve(img);
}
})
}, config);
Output:
https://i.stack.imgur.com/5YUBcm.png
Is there a way to prevent this behavior?