使用 rel preload 预加载字体

preloading font with rel preload

我正在使用 <link> HTML 标签预加载字体,并将 rel 属性设置为 preload如以下代码片段所示;

<link rel="preload" href="fonts/32ADEO.woff2" as="font" type="font/woff2">

虽然这通过加载字体按预期工作,但它会再次加载。

Google Chrome 浏览器中网络选项卡的屏幕截图显示字体加载两次 - 见下文;

此外,我在 Google Chrome 浏览器控制台选项卡中收到以下警告;

The resource https://example.com/new-v8/fonts/32A0E0.woff2 was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it Please make sure it has an appropriate 'as' value and it is preloaded intentionally.

我做错了什么,我该如何解决?

您的 preload-Tag 采用参数 "crossorigin",必须为 Webfonts 提供该参数,即使它们与您的网站位于同一主机上。

参见 https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content#Cross-origin_fetches or https://www.smashingmagazine.com/2016/02/preload-what-is-it-good-for/#early-loading-of-fonts

不知道我是否正在重新打开这里已经解决的问题,但我只是想提一下,您需要将 rel="preload" 链接放在加载字体的源之后,例如CSS 文件。

我在尝试加载预加载 google 字体时不断收到警告。

原来我没有注意到字体是作为样式从 google 加载的。我通过设置 as="style' 然后使用 rel="stylesheet preload prefetch" 解决了这个问题。

参见下面的代码示例:

<link 
 as="style"
 rel="stylesheet preload prefetch" 
 href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" 
 type="text/css" 
 crossorigin="anonymous" />

编码愉快=)

就我而言,更改为 rel="stylesheet preload" 对 Chrome -

有效

这里是 WORKED -

的最低限度

<link rel="stylesheet preload" href="path/to/stylesheet" as="style" />

什么没用是-

<link rel="preload" href="path/to/stylesheet" as="style" />

我玩得更开心了。除了这个警告,我发现我的浏览器同时下载 woffwoff2,尽管它应该只下载 woff2。更改 @font-facesrc 描述符的顺序对我有帮助。最后,我的解决方案看起来像这样:

<link href="/assets/fira-sans-condensed-v5-max-regular.woff2" rel="preload" as="font" type="font/woff2" crossorigin>
<link href="/assets/bundle.css" rel="stylesheet">

@font-face
{
    font-display: swap;
    font-family: "Fira Sans Condensed";
    font-style: normal;
    font-weight: 400;
    src: url("/assets/fira-sans-condensed-v5-max-regular.woff") format("woff");
    src: url("/assets/fira-sans-condensed-v5-max-regular.woff2") format("woff2");
}

我 运行 使用自托管字体解决了这个问题。我是这样预加载的:

<link rel="preload" href="/fonts/SomeFont.woff2" as="font" type="font/woff2" crossorigin>

问题是 webpack 正在向已编译的 css 字体路径添加哈希。

/* Before */
@font-face {
    font-family: "SomeFont";
    src: url("../fonts/SomeFont.woff2") format("woff2");
}

/* After (Webpack Output) */
@font-face {
    font-family: "SomeFont";
    src: url("../fonts/SomeFont.woff2?7d18a001dd0b6e04c2393") format("woff2");
}

所以我在预加载标签中添加了相同的哈希值,问题就解决了!

<link rel="preload" href="/fonts/SomeFont.woff2?7d18a001dd0b6e04c2393" as="font" type="font/woff2" crossorigin>