I Have added an Intersection Observer for image lazy loading. But for some reason if a div
element is present on the viewport lesser than 50% visibility the Intersection Observer isn't loading the image.
I want to load the image even when it's present 0% to 100% on the viewport. Here is my IntersectionObserver instance:
import {useEffect} from "react";
let listenerCallbacks = new WeakMap();
let observer;
function handleIntersections(entries) {
entries.forEach(entry => {
if (listenerCallbacks.has(entry.target)) {
let cb = listenerCallbacks.get(entry.target);
if (entry.isIntersecting || entry.intersectionRatio > 0) {
observer.unobserve(entry.target);
listenerCallbacks.delete(entry.target);
cb();
}
}
});
}
function getIntersectionObserver() {
if (observer === undefined) {
observer = new IntersectionObserver(handleIntersections, {
root: null,
rootMargin: "0px",
threshold: [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
});
}
return observer;
}
export function useIntersection(elem, callback) {
useEffect(() => {
let target = elem.current;
let observer = getIntersectionObserver();
listenerCallbacks.set(target, callback);
observer.observe(target);
return () => {
listenerCallbacks.delete(target);
observer.unobserve(target);
};
}, []);
}
Current result:
What I want:
Having threshold: [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
would run the callback every time visibility passes another 10%, so you would be over-fetching.
Since you want to fetch as soon as a tiny bit of the div
is visible, set the threshold
to 0, like threshold:0
, and change your if
statement inside handleIntersections
to:
if (entry.isIntersecting)
Lastly it's also related to how fast you are scrolling and how fast your back end is responding, and on how big the image is.
Reference on mdn .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.