@@ -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+
2634function 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