Skip to content

Commit d048ed2

Browse files
bubachoDevrocks Digital
authored andcommitted
fix(web): fallback when requestIdleCallback is unavailable
1 parent 50a7b47 commit d048ed2

1 file changed

Lines changed: 16 additions & 12 deletions

File tree

apps/web/core/components/core/render-if-visible-HOC.tsx

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,14 @@ type Props = {
2323
forceRender?: boolean;
2424
};
2525

26+
const runIdleTask = (callback: () => void) => {
27+
if (typeof window !== "undefined" && typeof window.requestIdleCallback === "function") {
28+
window.requestIdleCallback(callback, { timeout: 300 });
29+
return;
30+
}
31+
globalThis.setTimeout(callback, 0);
32+
};
33+
2634
function RenderIfVisible(props: Props) {
2735
const {
2836
defaultHeight = "300px",
@@ -47,14 +55,13 @@ function RenderIfVisible(props: Props) {
4755

4856
// Set visibility with intersection observer
4957
useEffect(() => {
50-
if (intersectionRef.current) {
58+
const target = intersectionRef.current;
59+
if (target) {
5160
const observer = new IntersectionObserver(
5261
(entries) => {
5362
//DO no remove comments for future
54-
if (typeof window !== undefined && window.requestIdleCallback && useIdletime) {
55-
window.requestIdleCallback(() => setShouldVisible(entries[entries.length - 1].isIntersecting), {
56-
timeout: 300,
57-
});
63+
if (typeof window !== "undefined" && useIdletime) {
64+
runIdleTask(() => setShouldVisible(entries[entries.length - 1].isIntersecting));
5865
} else {
5966
setShouldVisible(entries[entries.length - 1].isIntersecting);
6067
}
@@ -64,20 +71,17 @@ function RenderIfVisible(props: Props) {
6471
rootMargin: `${verticalOffset}% ${horizontalOffset}% ${verticalOffset}% ${horizontalOffset}%`,
6572
}
6673
);
67-
observer.observe(intersectionRef.current);
74+
observer.observe(target);
6875
return () => {
69-
if (intersectionRef.current) {
70-
// eslint-disable-next-line react-hooks/exhaustive-deps
71-
observer.unobserve(intersectionRef.current);
72-
}
76+
observer.unobserve(target);
7377
};
7478
}
75-
}, [intersectionRef, children, root, verticalOffset, horizontalOffset]);
79+
}, [intersectionRef, root, verticalOffset, horizontalOffset, useIdletime]);
7680

7781
//Set height after render
7882
useEffect(() => {
7983
if (intersectionRef.current && isVisible && shouldRecordHeights) {
80-
window.requestIdleCallback(() => {
84+
runIdleTask(() => {
8185
if (intersectionRef.current) placeholderHeight.current = `${intersectionRef.current.offsetHeight}px`;
8286
});
8387
}

0 commit comments

Comments
 (0)