html - 如果本地不存在如何预加载字体?

标签 html css fonts preload

在我的网站上,我想努力尽可能减小页面大小。因此,在 Apple 设备上 - 我想使用 native 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 代码存在问题,速度很慢并且无法预加载。

现在是的,我想我可以为所有页​​面 View 预加载 Roboto 字体,但这似乎完全浪费。

关于如何做到这一点的想法?

最佳答案

实现此目的的一种方法是通过 JS 和 CSS Font Loading API。

您可以首先尝试从 FontFace 实例加载本地“San Francisco”字体,如果失败,则加载 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>

关于html - 如果本地不存在如何预加载字体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65056277/

相关文章:

javascript - 打开按钮时停止图像移动

javascript - 如何延迟div中背景图片的显示

html - 如何相对于父级定位按钮?

html - 表格边框 CSS 在浏览器之间表现不同

c# - 如何在我的 .Net Web 应用程序中使用/调用 ttf2eot(用于将 TTF 字体格式转换为 EOT 类型的应用程序)

html - :hover 上链接周围的等长背景框

html - 垂直对齐 Font Awesome 图标旁边的文本并对齐

html - Iphone 文本位置问题

css - 我如何让字体像这样平滑显示?

css - @font-face 在 Firefox 或 IE 中不工作——我怎么知道为什么?