javascript - 如何在 NextJs 中缓存字体?

标签 javascript reactjs caching next.js

我试图向用户显示两种字体,但没有 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>

样式.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;
}

最佳答案

使用 next.js 自定义服务器,您可以为每个文件设置缓存控制。

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');
}

对于 Google Font,它看起来像缓存控制已经设置。

关于javascript - 如何在 NextJs 中缓存字体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57272055/

相关文章:

javascript - Highcharts yAxis自适应问题

javascript - SuiteScript 2.0 TypeError 无法调用未定义的方法 "getValue"

javascript - 为什么我不能用 javascript 清除输入字段?

javascript - 我如何居中 Bootstrap 的轮播?不是图片,是轮播本身

reactjs - 在 React 应用程序中测试 Select 元素

javascript - 在 Jest 中模拟动态 html 元素

Javascript - 使用 ESLINT 6 获取 json 数组的出现次数

Mendix 中的缓存和 AOP : is there a uniform or standardized approach for server-side caching within a Mendix application?

caching - 英伟达 CUDA : cache L2 and multiple kernel invocations

objective-c - RestKit - fetchFromDataStore(缓存)问题