Front-page lazy-load fixes and improvements #6388

Merged
infinite-persistence merged 3 commits from ip/front.page.lazy.load.2 into master 2021-07-05 10:04:34 +02:00
Showing only changes of commit 9745d6df3e - Show all commits

View file

@ -2,7 +2,7 @@
import React from 'react';
import debounce from 'util/debounce';
const DEBOUNCE_SCROLL_HANDLER_MS = 25;
const DEBOUNCE_SCROLL_HANDLER_MS = 50;
type Props = {
children: any,
@ -14,12 +14,13 @@ export default function WaitUntilOnPage(props: Props) {
const ref = React.useRef();
const [shouldRender, setShouldRender] = React.useState(false);
React.useEffect(() => {
const handleDisplayingRef = debounce((e) => {
const shouldElementRender = React.useCallback((ref) => {
const element = ref && ref.current;
if (element) {
const bounding = element.getBoundingClientRect();
if (
bounding.width > 0 &&
bounding.height > 0 &&
bounding.bottom >= 0 &&
bounding.right >= 0 &&
// $FlowFixMe
@ -27,20 +28,34 @@ export default function WaitUntilOnPage(props: Props) {
// $FlowFixMe
bounding.left <= (window.innerWidth || document.documentElement.clientWidth)
) {
return true;
}
}
return false;
}, []);
// Handles "element is already in viewport when mounted".
React.useEffect(() => {
setTimeout(() => {
if (!shouldRender && shouldElementRender(ref)) {
setShouldRender(true);
}
}
}, 500);
}, []); // eslint-disable-line react-hooks/exhaustive-deps
if (element && !shouldRender) {
window.addEventListener('scroll', handleDisplayingRef);
return () => window.removeEventListener('scroll', handleDisplayingRef);
// Handles "element scrolled into viewport".
React.useEffect(() => {
const handleDisplayingRef = debounce(() => {
if (shouldElementRender(ref)) {
setShouldRender(true);
}
}, DEBOUNCE_SCROLL_HANDLER_MS);
if (ref) {
handleDisplayingRef();
if (ref && ref.current && !shouldRender) {
window.addEventListener('scroll', handleDisplayingRef);
return () => window.removeEventListener('scroll', handleDisplayingRef);
}
}, [ref, setShouldRender, shouldRender]);
}, [ref, setShouldRender, shouldRender, shouldElementRender]);
const render = props.skipWait || shouldRender;