【问题标题】:How to preload material icons using rel=preload?如何使用 rel=preload 预加载素材图标?
【发布时间】:2019-01-23 05:37:24
【问题描述】:

我正在尝试使用 google lighthouse 优化我的网页。

报告说在导入 Material Design 图标的链接上使用 rel=preloads。

我尝试使用语法预加载它们。

<link rel="preload" href="" as="style" crossorigin>

我也尝试过使用 as 字体进行预加载。类型为 woff、woff2 和 ttf。它们似乎都不起作用。我还添加了 crossorigin 和 crossorigin="anonymous" 但仍然没有进展。

这些是我的实际链接。我想同时导入它们。

<link rel="preload" href="https://cdnjs.cloudflare.com/ajax/libs/material-design-iconic-font/2.2.0/css/material-design-iconic-font.min.css" as="style">
<link rel="preload" href="https://fonts.googleapis.com/icon?family=Material+Icons" as="font" type="font/woff" crossorigin>

应该如何将这些链接与预加载一起使用?

【问题讨论】:

标签: html css fonts icons preload


【解决方案1】:

我注意到在获取 url 时,Google 字体会在链接末尾放置一个 &amp;display=swap。因此,当我们将其更改为 display=block 时,它会更改服务器端的 css 文件:

font-display: block;

所以像这样使用它:

<link href="https://fonts.googleapis.com/icon?family=Material+Icons&display=block" rel="stylesheet">

【讨论】:

    【解决方案2】:

    我希望 Google 在它的字体指南中准备好预加载信息,但只有普通的 CSS 示例 [1]。

    无论如何,我通过添加以下内容破解了解决方案:

    &lt;link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Material+Icons&amp;amp;display=swap" media="print" onload="this.media='all'" crossorigin&gt;

    (对于不支持的预加载,这似乎是一个很好的后备机制,所以无论如何都有它很好)。

    另外,为了摆脱图标名称的“闪烁”,我正在使用代码点 [3]。像这样:

    &lt;i class="material-icons"&gt;&amp;#xE87C;&lt;/i&gt;(而不是&lt;i class="material-icons"&gt;face&lt;/i&gt;)。

    这样,在字体加载过程中,我会得到几乎不可见的符号,例如 □ 而不是完整的“脸”。

    [1] - https://google.github.io/material-design-icons/

    [2] - https://csswizardry.com/2020/05/the-fastest-google-fonts/

    [3] - https://github.com/google/material-design-icons/blob/master/iconfont/codepoints

    【讨论】:

      【解决方案3】:

      这对我有用:

      <link 
        rel="preload"
        as="style" onload="this.rel = 'stylesheet'"
        href="https://fonts.googleapis.com/icon?family=Material+Icons">
      

      【讨论】:

      • 这很聪明,但我不认为我会推荐这种方法,除非是万不得已。
      【解决方案4】:
      <link rel="preload" href="https://fonts.gstatic.com/s/materialicons/v41/flUhRq6tzZclQEJ-Vdg-IuiaDsNZ.ttf" as="font" type="font/ttf" crossorigin="anonymous">
      
      <style>
        @font-face {
          font-family: 'Material Icons';
          font-style: normal;
          font-weight: 400;
        }
        .material-icons {
          font-family: 'Material Icons';
          font-weight: normal;
          font-style: normal;
          font-size: 24px;
          line-height: 1;
          letter-spacing: normal;
          text-transform: none;
          display: inline-block;
          white-space: nowrap;
          word-wrap: normal;
          direction: ltr;
        }
      
      </style>
      

      【讨论】:

        猜你喜欢
        • 2018-09-15
        • 2018-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-25
        • 2018-04-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多