skip to Main Content

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>
  )

3

Answers


  1. 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.

    Login or Signup to reply.
  2. 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);
    }, []);
    
    Login or Signup to reply.
  3. 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}
         </>
        );
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search