webフォントが使えない端末では(Android等)ローカルフォントを読み込む方法
Googleフォントなどを読み込む際に、Android端末などではwebフォントが反映されないことがあると思います。
しかし、IOSなど正常に読み込める端末ではCDNを使ったほうが圧倒的に速度が速いため、フォントが読み込める端末ではCDNを、読み込めない端末ではローカルフォントを読み込めるようにするコードを記述しておきます。
<script>
// assetsディレクトリのパスを指定(これはあっても無くてもいいですがあると便利)
const assetsUrl = "https://xxx.com/assets/";
</script>
const LoadWebFont = () => {
const fontUrl = 'https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@100..900&display=swap';
fetch(fontUrl)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok.');
}
return response.text();
})
.then(() => {
// Webフォントのロードに成功した場合
document.head.insertAdjacentHTML('beforeend', `
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@100..900&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Cormorant+Garamond:ital,wght@0,300;0,400;0,500;0,600;0,700;1,300;1,400;1,500;1,600;1,700&family=Noto+Sans+JP:wght@100..900&display=swap" rel="stylesheet">
`);
})
.catch(() => {
// Webフォントのロードに失敗した場合(ローカルフォントを使用)
document.head.insertAdjacentHTML('beforeend', `
<style>
@font-face {
font-family: "NotoSansJP_Variable";
src: url("${assetsUrl}fonts/NotoSansJP-VariableFont_wght.eot") format('eot'),
url("${assetsUrl}fonts/NotoSansJP-VariableFont_wght.woff") format('woff'),
url("${assetsUrl}fonts/NotoSansJP-VariableFont_wght.ttf") format('truetype');
font-weight: 100 900;
font-display: swap;
}
@font-face {
font-family: "CormorantGaramond_W5";
src: url("${assetsUrl}fonts/CormorantGaramond-Medium.ttf") format("truetype");
font-display: swap;
}
</style>
`);
});
};