I want to render my image only when the user has seen it or when the image element is visible within the user viewport. I already tried it, but the image is only rendered when I already passed all the image element, not one by one when i scroll.
I create a custom directive and place it on my parent div.
This is my intersection observer using Vue directive:
inserted: el => {
let arrayChildren = Array.from(el.children)
const config = {
root: null,
rootMargin: '0px',
threshold: 1.0,
}
let observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.src = entry.target.dataset.src
observer.unobserve(entry.target)
}
})
}, config)
function getAllImgQuery() {
let imageArray = []
arrayChildren.forEach(element => {
if (element.nodeName === 'IMG') {
imageArray.push(element)
}
})
return imageArray
}
let imageQuery = getAllImgQuery()
imageQuery.forEach(image => {
observer.observe(image)
})
},
And this is my Vue component:
<template>
<div id="image-container">
<div class="product">
<figure class="image-wrapper" v-lazyload>
<img :data-src="url" style="margin-top: 100px">
<img :data-src="url" style="margin-top: 100px">
<img :data-src="url" style="margin-top: 100px">
<img :data-src="url" style="margin-top: 100px">
<img :data-src="url" style="margin-top: 100px">
<img :data-src="url" style="margin-top: 100px">
</figure>
</div>
</div>
</template>
<script>
import lazyLoadDirective from "../directives/lazyLoadImage.js";
export default {
data() {
return {
url:
"https://s2.reutersmedia.net/resources/r/?m=02&d=20190823&t=2&i=1422065068&w=1200&r=LYNXNPEF7M1OI"
};
},
directives: {
lazyload: lazyLoadDirective
}
};
</script>
At the end, the six images loads at the same time only when I already seen it or intersect it (when I was at the bottom of the page). How can i load my image one by one only after i scroll pass it ?