如何仅在本地不存在字体时才预加载字体?



在我的网站上,我想尽可能地缩小页面大小。因此,在苹果设备上,我想使用本机San Francisco字体显示我的网站。在所有其他设备上,我想显示(极其相似的(Roboto字体。

Roboto的伟大之处在于它在本地安装了Android。。。因此,如果字体已经存在,我不想安装它。

我想做的是,在下面的伪代码中描述什么

if ("San Francisco" or "Roboto" not installed locally) {
// download Robot (and preload it for super fast performance)
<link rel="preload" as="font" href="/assets/fonts/roboto.woff2" type="font/woff2" crossorigin/>
}

我完全意识到,在我的CSS中,它已经能够回退到另一种字体,比如

body { font:normal 1em -apple-system,"Roboto",sans-serif;}

上面的CSS代码的问题是速度慢而且没有预加载。

现在是的,我想我可以为所有页面视图预装Roboto字体,但这似乎完全是浪费。

想知道我该怎么做吗?

实现这一点的一种方法是通过JS和CSS字体加载API。

您可以从尝试加载本地";旧金山";FontFace实例中的字体,如果失败,则加载Roboto回退
但是这样做,我们失去了链接预加载的一些优势,我们可能会面临无样式内容的闪光。

(async () => {
const sanfrancisco = new FontFace( "San Francisco", "local('San Francisco')" );
try {
await sanfrancisco.load();
console.log( "'San Francisco' font is available on this system" );    
document.fonts.add( sanfrancisco );
}
catch( err ) {
console.log( "'San Francisco' font is not available on this system" );
// use the local version
// or fallback to the online one if not available
const roboto = new FontFace( "Roboto", `local(Roboto),
url(https://fonts.gstatic.com/s/roboto/v20/KFOmCnqEu92Fr1Mu4mxKKTU1Kg.woff2)
` );
await roboto.load();
console.log( "Roboto font loaded" );
document.fonts.add( roboto );
}
document.body.classList.add( "font-loaded" ); // avoid FOUC
})();
body:not(.font-loaded) {
opacity: 0;
}
.my-font {
font-family: 'San Francisco','Roboto';
}
The following paragraph
<p class="my-font">uses either San Francisco or Roboto.</p>

最新更新