5

I have two fonts which I am trying to display to the user, while there's no FOIT, and instead I am having a FOUT I'd like user not to re-download fonts each time they revisit the page.

I have added Font observer to add additional FOUT fallback functionality. _document.js

  componentWillMount() {
    if (process.browser) {
      const html = document.documentElement;
      html.classList.add('fonts-loading');
      const fontPoppins = new FontFaceObserver('Poppins');
      fontPoppins.load(null, 5000).then(() => {
        console.log('Poppins font has loaded.');
        html.classList.remove('fonts-loading');
        html.classList.add('fonts-loaded');
      }).catch(() => {
        html.classList.remove('fonts-loading');
        html.classList.add('fonts-failed');
      });
      const fontAvenir = new FontFaceObserver('Avenir');
      fontAvenir.load(null, 5000).then(() => {
        console.log('Avenir font has loaded.');
      }).catch(() => {
        html.classList.remove('fonts-loading');
        html.classList.add('fonts-failed');
      });
    }
  }
... (more code here)

render ( code here ) ...

// Additional FOUT?
        <Head>
          <link
            href="https://fonts.googleapis.com/css?family=Poppins:200,300,400,600,700,800,900&display=swap"
            rel="preload"
            as="font"
          />
           ... (more code here)
        </Head>

styles.css

html {
  font-family: sans-serif;
  -webkit-font-smoothing: antialiased;
}

.fonts-loaded html {
  font-family: Avenir, sans-serif;
}


@font-face {
  font-family: Avenir;
  src: url('/static/fonts/Avenir.ttc');
  font-display: swap;
  font-style: normal;
}

@font-face {
  font-family: Poppins;
  src: url('/static/fonts/Poppins-Regular.ttf');
  font-weight: 400;
  font-style: normal;
  font-display: swap;
}

1 Answer 1

1

Use next.js custom server and you can set cache-control for each files.

https://github.com/zeit/next.js/#custom-server-and-routing

const parsedUrl = parse(req.url, true)
const { pathname, query } = parsedUrl

if(pathname === '/static/fonts/Avenir.ttc' || pathname === '/static/fonts/Poppins-Regular.ttf') {
    res.setHeader('Cache-Control', 'public,max-age=31536000');
}

For Google Font its look like cache-control had set already.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.