1

So this is what I'm currently working on: https://sipkin-portfolio-v2.netlify.app/

When I open this website it shows the default sans-serif font for a split second and then it loads Bebas Neue. I would like to know if I could load the font from Google first and then show the page content. This is my _document.js file:

import { ServerStyleSheet } from "styled-components";

export default class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const sheet = new ServerStyleSheet();
    const originalRenderPage = ctx.renderPage;

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) =>
            sheet.collectStyles(<App {...props} />),
        });

      const initialProps = await Document.getInitialProps(ctx);
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      };
    } finally {
      sheet.seal();
    }
  }
  render() {
    return (
      <Html lang="en">
        <Head>
          <link rel="preconnect" href="https://fonts.googleapis.com" />
          <link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin />
          <link
            href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Poppins:wght@400;700&display=swap"
            rel="stylesheet"
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}
Aleksa
  • 73
  • 1
  • 4
  • Does this answer your question? [preloading font with rel preload](https://stackoverflow.com/questions/49674092/preloading-font-with-rel-preload) – Rob Mar 12 '22 at 19:26
  • @Rob When I try that, I get this error: The resource https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Poppins:wght@400;700&display=swap was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate `as` value and it is preloaded intentionally. – Aleksa Mar 12 '22 at 19:34

1 Answers1

1

Try changing the display strategy for your fonts to optional.

<link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Poppins:wght@400;700&display=optional"
rel="stylesheet" />

See here

Youzef
  • 616
  • 1
  • 6
  • 23
  • Tried using this one already. All it does is not load the font on the first load, but it does load it after refreshing the page – Aleksa Mar 12 '22 at 19:25
  • Note that the [](https://html.spec.whatwg.org/dev/semantics.html#the-link-element) tag does not use and does not need a closing slash and never has in any HTML specification. – Rob Mar 12 '22 at 19:27
  • Thanks for the tip, but I needed to use it because NextJS was throwing an error. – Aleksa Mar 12 '22 at 19:29
  • 1
    @Aleksa Yeah, I didn't notice that. I don't know why NextJS doesn't follow the HTML specification. – Rob Mar 12 '22 at 19:30