Pull-up loading is often used in H5 mobile development, as in
For those of you interested, check out react-LoadMore, which is very easy to use!
Generally, what we do is to judge the scrollTop and clientHeight and compare the scrollHeight to find out whether it is at the bottom.
Refer to detect – if – browser window – is scrolled – to – bottom
let scrollTop =
(document.documentElement && document.documentElement.scrollTop) ||
document.body.scrollTop;
let scrollHeight =
(document.documentElement && document.documentElement.scrollHeight) ||
document.body.scrollHeight;
let clientHeight =
document.documentElement.clientHeight || window.innerHeight;
let scrolledToBottom =
Math.ceil(scrollTop + clientHeight) >= scrollHeight;
Copy the code
However, there are various issues with this approach on mobile devices, including browser versions, ios, and Android.
Recently found a relatively simple way ~
useIntersection Observer
This method is very simple. All it needs to do is to generate a IntersectionObserver for the element and monitor the element, and then judge the intersectionRatio ratio of the element through the callback of monitoring. This is the core code.
componentDidMount() {
if(! this.props.Footer) this._svgaLoad(); try { const node = document.getElementById('bottom')
this.observer = new IntersectionObserver(this.insideViewportCb);
this.observer.observe(node);
} catch (err) {
console.log("err in finding node", err);
}
window.addEventListener("scroll", this.handleOnScroll); } insideViewportCb(entries) { const { fetching, onBottom } = this.props; Entries. forEach(Element => {// in viewportif (element.intersectionRatio > 0&&!fetching) {
onBottom();
}
});
}
Copy the code
Given a style at the bottom, IntersectionObserver can be used to monitor it and trigger loading if it is judged to be in viewPortPort!
For those of you interested, check out react-LoadMore, which is very easy to use!