如何将 <link rel=preload> 应用到@font-face?

How to apply <link rel=preload> to @font-face?

Google 建议“考虑使用 <link rel=preload> 来优先获取当前在页面加载后请求的资源。”但是没有示例说明我们在使用 @font-face 方法时应该如何使用它。 我应该改用 HTML 字体加载方法吗?

我现在使用什么来加载我的自定义字体:

@font-face {
    font-family: 'Custom';
    src: url("../fonts/Custom-Bold.eot");
    src: local("☺"), url("../fonts/Custom-Bold.woff") format("woff"), url("../fonts/Custom-Bold.ttf") format("truetype"), url("../fonts/Custom-Bold.svg") format("svg");
    font-weight: 600;
    font-style: normal;
    font-display: swap;
  }
  
@font-face {
    font-family: 'Custom';
    src: url("../fonts/Custom-Heavy.eot");
    src: local("☺"), url("../fonts/Custom-Heavy.woff") format("woff"), url("../fonts/Custom-Heavy.ttf") format("truetype"), url("../fonts/Custom-Heavy.svg") format("svg");
    font-weight: 800;
    font-style: normal;
    font-display: swap;
  }

建议将 preload 应用于您的 link 标签,而不是样式本身。

因此,例如,如果您的 css 代码位于名为“fonts.css”的文件中,您可以将以下行放在 HTML 中您要访问它的位置:

<link rel="preload" as="style" href="fonts.css">

然后您将告诉页面预加载您的“fonts.css”文件。 "as" 这里应该是实际资源是什么,所以如果你实际上想使用字体文件而不是样式 sheet,只需更改 "as='style'”到“as='font'”。