预加载Google字体 [英] Preloading Google Fonts

查看:73
本文介绍了预加载Google字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

灯塔审计建议我预先加载关键请求,特别是我在React应用程序中使用的两种Google字体.灯塔成员建议使用:< link rel ="preload" as ="style" href ="https://fonts.googleapis.com/css?family=Open+Sans|Roboto:700" crossorigin>< link rel ="preconnect" href ="https://fonts.gstatic.com/" crossorigin>

我知道它是在发出请求,因为我在瀑布中看到了它,并且收到了以下控制台警告:

资源 https://fonts.googleapis.com/css?family = Open + Sans | Roboto:700 已使用链接预加载进行了预加载,但在窗口加载事件发生后的几秒钟内未使用.请确保它具有适当的as值并且是有意预加载的.">

不幸的是,这两种字体不再显示在我的应用程序中.我是否需要在CSS中使用@ font-face或类似的东西定义这些?

解决方案

正确加载字体的正确方法是同时添加 preload 链接和 stylesheet .基于 MDN 的简化示例如下:

 < head>< meta charset ="utf-8">< title>预加载字体</title>< link rel ="preload" href ="https://fonts.googleapis.com/css?family=Roboto&display=swap" as ="style">< link rel ="stylesheet" href ="https://fonts.googleapis.com/css?family=Roboto&display=swap"></head><身体></body> 

在上面的示例中, preload 链接将发送一个请求以获取字体,而不管客户端上是否安装了该字体,然后使用 stylesheet 链接进行正确加载并使用它.

preload 是一种告诉浏览器可能将需要资源的方法,因此无论是否需要它,无论是需要还是决定使用它,都可以请求该资源.

更多的信息

Light House audit is suggesting that I preload key requests, specifically the two google fonts that I'm using in my React app. A Light House member suggested using: <link rel="preload" as="style" href="https://fonts.googleapis.com/css?family=Open+Sans|Roboto:700" crossorigin> <link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin>

I know it's making the request because I see it in the waterfall and I get this console warning:

"The resource https://fonts.googleapis.com/css?family=Open+Sans|Roboto:700 was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate as value and it is preloaded intentionally."

Unfortunately the two font do not display in my app anymore. Do I need to define these in my CSS with @font-face or something like that?

解决方案

The correct way to preload a font would be by adding both a preload link and a stylesheet. A simplified example, based on MDN is as follows:

<head>
  <meta charset="utf-8">
  <title>Preloading fonts</title>

  <link rel="preload" href="https://fonts.googleapis.com/css?family=Roboto&display=swap" as="style">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto&display=swap">
</head>

<body>
</body>

In the above example, the preload link will send a request to fetch the font regardless of it being installed or not on the client and then use the stylesheet link to properly load and use it.

preload is more of a way to tell the browser that a resource will probably be needed, so that it will be requested regardless and then, if you need it or decide to use it, you can.

Further information

这篇关于预加载Google字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆