简体   繁体   中英

Load font from googleapis after page loading in react.js

I work with an SEO consultant for SEO optimizations and faster page loading. He said that the fonts and some javascript libraries should arrive after the page loads. Thus, the website will load faster, but when I viewed it on the internet, I could not find much. I use React js and have no idea about seo improvements so much. I call the font as follows in the header component. the header component is called other nested component regarding HeaderLayout component and the components calling HeaderLayout to access other page is called. There is any way to load these after page load?

return (
    <Head>      
      <link
        rel="stylesheet"
        href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
        integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z"
        crossOrigin="anonymous"
      />
      <link
        rel="stylesheet"
        href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;700&amp;display=swap"
      />

      <link
        rel="icon"
        type="image/x-icon"
        sizes="32x32"
        href="/icons/favico.ico"
      />
      <link rel="canonical" href={routerUrlWithoutQuery} />
      <meta name="color-scheme" content="light" />
    </Head>
  )

Just set an invalid value for media attribute in <link> and later set it to all on page load, like so:

<link rel="stylesheet" href="link here" media="none" onload="if(media!='all')media='all'">

When a media query evaluates to false, the browser will still download the stylesheet, but it won't wait for the content to be available before rendering the page.

Maybe you could append it to the head in a useEffect?

Example:

useEffect(() => {
  const link = document.createElement("link");
  link.rel = "stylesheet";
  link.href =
    "https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css";
  link.integrity =
    "sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z";
  link.crossOrigin = "anonymous";
  document.head.appendChild(link);
}, []);

Another approach is to download the font locally. From es6, you can use document.fonts to check when the fonts are loaded. It would look like something like this:

const MainPage: NextPage = () => {
 const [show, setShow] = useState<boolean(false);

 useEffect(() => {
   document.fonts.ready.then(() => {
   setShow(true);
  });
 }, []);

const app = (<>This is an App</>);

return (
 <>
   {show && app}
 </>
);
};

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