简体   繁体   中英

React - wait for assets from CDN before showing component?

I'm loading a stylesheet from an external CDN in order to style one page in React. The stylesheet link is injected to <head > using react-helmet :

<Helmet>
  <link rel="stylesheet" href="example.com/site.css" />
</Helmet>

Unfortunately, before the stylesheet loads there's a FOUC visible for a few milliseconds. I'm integrating an outside service so I can't really load the style in any other way.

I've tried using useEffect hook and render page only when its ready like so:

const [isPageReady, setPageReady] = useState(false);

useEffect(() => {
  setPageReady(true);
}, []);

return ( 
  isPageReady && ( // my page );
)

But the FOUC is still there. Is there a way to wait for the stylesheet to load before I display the page?

The essential problem is that the CSS is still loading while the first components are already on the screen. Usually this takes only a tiny fraction of a second, so you may just want to hide your components until the DOM is fully rendered.

To do this, you can encapsulate everything in a top-level div that's invisible until document.readyState equals complete. This way, the rendering of the DOM will not be visible and the first exposed screen will be a fully rendered document.

const [visible, setVisible] = useState('hidden');

// This will run one time after the component mounts
useEffect(() => {
  const onPageLoad = () => {
    setVisible('visible');
  };
  // Check if the page has already loaded
  if (document.readyState === 'complete') {
    onPageLoad();
  } else {
    window.addEventListener('load', onPageLoad);
    // Remove the event listener when component unmounts
    return () => window.removeEventListener('load', onPageLoad);
  }
}, []);

return (
  <div style={{ visibility: visible }}>
    <YourPage />
  </div>
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM