화면을 새로고침했을 때 폰트가 다음처럼 움찔하는(FOUT) 현상이 있었다.
사용자 경험에 좋지 않을 것 같아서 수정해보기로 했다.
yarn add -D vite-plugin-html
// src/utils/fontPreload.ts
import { readdirSync } from 'fs';
import { resolve } from 'path';
import { HtmlTagDescriptor } from 'vite';
const fontsDirectory = resolve(__dirname, '../styles/fonts/woff2'); // 경로 적절히 수정
const fontFiles = readdirSync(fontsDirectory).filter((file) =>
file.endsWith('.woff2') // 불러올 폰트
);
export const injectFontsToHead: HtmlTagDescriptor[] = fontFiles.map(
(fontFile) => ({
injectTo: 'head',
tag: 'link',
attrs: {
rel: 'preload',
href: `./styles/fonts/woff2/${fontFile}`, // 적절히
as: 'font',
type: 'font/woff2',
crossOrigin: 'anonymous',
},
})
);
defineConfig
의 plugins
속성을 찾았다.createHtmlPlugin
메서드를 사용해서 위 파일에서 작성한 injectFontsToHead를 설정해주었다.새로고침 시 항상 최상단으로 스크롤되도록 처리(ScrollToTop)했기 때문에 첫 렌더링 때 보이는 폰트는 Header 컴포넌트의 Pretendard-Medium 뿐이었다.
첫 화면에 다른 굵기의 폰트가 보이게 될 경우 똑같이 index.html에 추가해주면 될 듯 하다.
(index.html 작성 시 참고한 Stackoverflow 내용)
새로고침 시 폰트의 움찔하는 현상이 사라졌다.