[英]How to cache fonts in NextJs?
我有兩種字體,我試圖向用戶顯示,而沒有 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>
樣式文件
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,它的緩存控制看起來已經設置好了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.