diff --git a/apps/comments-ui/src/App.tsx b/apps/comments-ui/src/App.tsx index 74635aa618..d15c35e425 100644 --- a/apps/comments-ui/src/App.tsx +++ b/apps/comments-ui/src/App.tsx @@ -29,6 +29,8 @@ const App: React.FC = ({scriptTag}) => { popup: null }); + const iframeRef = React.createRef(); + const api = React.useMemo(() => { return setupGhostApi({ siteUrl: options.siteUrl, @@ -129,7 +131,7 @@ const App: React.FC = ({scriptTag}) => { }; }; - /** Initialize comments setup on load, fetch data and setup state*/ + /** Initialize comments setup once in viewport, fetch data and setup state*/ const initSetup = async () => { try { // Fetch data from API, links, preview, dev sources @@ -155,15 +157,39 @@ const App: React.FC = ({scriptTag}) => { } }; + /** Delay initialization until comments block is in viewport */ useEffect(() => { - initSetup(); - }, []); + const observer = new IntersectionObserver((entries) => { + entries.forEach((entry) => { + if (entry.isIntersecting) { + initSetup(); + if (iframeRef.current) { + observer.unobserve(iframeRef.current); + } + } + }); + }, { + root: null, + rootMargin: '0px', + threshold: 0.1 + }); + + if (iframeRef.current) { + observer.observe(iframeRef.current); + } + + return () => { + if (iframeRef.current) { + observer.unobserve(iframeRef.current); + } + }; + }, [iframeRef.current]); const done = state.initStatus === 'success'; return ( - + diff --git a/apps/comments-ui/src/components/ContentBox.tsx b/apps/comments-ui/src/components/ContentBox.tsx index bdafe8c1c1..34eaeeed0b 100644 --- a/apps/comments-ui/src/components/ContentBox.tsx +++ b/apps/comments-ui/src/components/ContentBox.tsx @@ -54,7 +54,7 @@ const ContentBox: React.FC = ({done}) => { }; return ( -
+
{done ? : }
); diff --git a/apps/comments-ui/src/components/Frame.tsx b/apps/comments-ui/src/components/Frame.tsx index cb692c37d6..64c898d602 100644 --- a/apps/comments-ui/src/components/Frame.tsx +++ b/apps/comments-ui/src/components/Frame.tsx @@ -15,7 +15,7 @@ type TailwindFrameProps = FrameProps & { /** * Loads all the CSS styles inside an iFrame. Only shows the visible content as soon as the CSS file with the tailwind classes has loaded. */ -const TailwindFrame: React.FC = ({children, onResize, style, title}) => { +const TailwindFrame = React.forwardRef>(function TailwindFrame({children, onResize, style, title}, ref: React.ForwardedRef) { const head = ( <>