[英]Intersection Observer isn't working elements having less than 50% visibility on viewport
I Have added an Intersection Observer for image lazy loading.我添加了一个 Intersection Observer 用于图像延迟加载。 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.但是由于某种原因,如果视口上的div
元素的可见性小于 50%,则 Intersection Observer 不会加载图像。
I want to load the image even when it's present 0% to 100% on the viewport.我想加载图像,即使它在视口上显示为 0% 到 100%。 Here is my IntersectionObserver instance:这是我的 IntersectionObserver 实例:
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.有threshold: [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
会在每次可见性再超过 10% 时运行回调,所以你会过度获取。
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:由于您想在div
的一小部分可见时立即获取,因此将threshold
设置为 0,例如threshold:0
,并将您的if
语句在handleIntersections
中更改为:
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.最后,它还与您滚动的速度、后端的响应速度以及图像的大小有关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.