我正在尝试使用谷歌灯塔优化我的网页。
报告称在导入 Material Design 图标的链接上使用 rel=preloads。
我尝试使用语法预加载它们。
<link rel="preload" href="" as="style" crossorigin>
我也尝试过使用字体进行预加载。类型为 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>
如何使用这些带有预加载的链接?
我希望 Google 在其字体指南中准备好预加载信息,但只有普通的 CSS 示例 [1]。
无论如何,我通过添加以下内容来破解解决方案:
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Material+Icons&display=swap" media="print" onload="this.media='all'" crossorigin>
(对于不支持的预加载,这似乎是一个很好的后备机制,所以无论如何拥有它都是很好的)。
此外,为了摆脱图标名称的“闪烁”,我使用代码点 [3]。像这样:
<i class="material-icons"></i>
(而不是<i class="material-icons">face</i>
)。
这样,在字体加载期间,我会得到几乎看不见的符号,如 □,而不是完整的“脸”。
[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
这对我有用:
<link
rel="preload"
as="style" onload="this.rel = 'stylesheet'"
href="https://fonts.googleapis.com/icon?family=Material+Icons">
我注意到 Google Fonts 在获取 url 时会在链接末尾放置一个
&display=swap
。因此,当我们将其更改为 display=block
时,它会在服务器端的 css 文件中进行更改:
font-display: block;
所以像这样使用它:
<link href="https://fonts.googleapis.com/icon?family=Material+Icons&display=block" rel="stylesheet">
可以通过在应用程序的入口页面上放置透明图标来预加载图标。如果入口页面不包含任何其他需要显示的图标,则效果很好。
index.html:
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons|Material+Icons+Outlined" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0" />
home.component.ts:
<span class="material-symbols-outlined transparent">home</span>
<span class="material-icons-outlined transparent">edit</span>
home.component.scss:
.transparent {
color: transparent;
}
<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>