如何在NextJs中缓存字体?

JavaScript React.js

古一

2020-03-24

我有两种字体要显示给用户,而没有FOIT,而是使用FOUT,我希望用户不要在每次重新访问页面时重新下载字体。

我添加了字体观察器以添加其他FOUT后备功能。_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;
}

第3212篇《如何在NextJs中缓存字体?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

0个回答

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android