[英]How to cache fonts in NextJs?
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.我有两种字体,我试图向用户显示,而没有 FOIT,相反,我有一个 FOUT,我希望用户不要在每次重新访问页面时重新下载字体。
I have added Font observer to add additional FOUT fallback functionality.我添加了字体观察器来添加额外的 FOUT 回退功能。 _document.js
_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;
}
Use next.js custom server and you can set cache-control for each files.使用 next.js 自定义服务器,您可以为每个文件设置缓存控制。
https://github.com/zeit/next.js/#custom-server-and-routing 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.对于 Google Font,它的缓存控制看起来已经设置好了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.