问题
I'm getting the diagnostic on PageSpeed Insights
Ensure text remains visible during webfont load
Leverage the font-display CSS feature to ensure text is user-visible while webfonts are loading. Learn more.
URL
Potential Savings
…v1/aWB4m0aac….woff2(fonts.gstatic.com) 10 ms
…v21/nuFvD-vYS….woff2(fonts.gstatic.com) 10 ms
…v13/6xK3dSBYK….woff2(fonts.gstatic.com) 10 ms
And I'm trying to correct it by changing
<link rel="stylesheet" href="https://fonts.googleapis.com" />
to
<link rel="stylesheet" href="https://fonts.googleapis.com/display=swap" />
But this actually throws a console error
I know that PageSpeed Insights recommends to add font-display: swap
to @fontface
, but I don't know what @fontface
is.
I'm using Bootstrap and Gatsby
I know there's also gatsby-plugin-web-font-loader
. Is there a way to use this to avoid this diagnostic?
These are all the times font-family shows up in my program. I'm using scss
so most of them are variables
I only specify a font once in my program, and I think bootstrap chooses the font the rest of the time
blockquote > p {
font-family: 'Montserrat', sans-serif;
}
Update, I'm using this plugin now
{
resolve: `gatsby-plugin-google-fonts`,
options: {
fonts: [
`Montserrat`,
`Helvetica Neue`,
`Helvetica`,
`Arial`
],
display: 'swap'
}
},
回答1:
@font-face
is a rule that allows you to use multiple font-family
rule instead of loading it in each selector.
Among all font plugin of fonts in Gatsby I recommend gatsby-plugin-google-fonts because it allows you to display and swap between fonts.
plugins: [
{
resolve: `gatsby-plugin-google-fonts`,
options: {
fonts: [
`limelight`,
`source sans pro\:300,400,400i,700` // you can also specify font weights and styles
],
display: 'swap'
}
}
]
It's really useful since it's preloading the font without affecting the display (due to the swap
property).
With Gatsby, <link rel="stylesheet" href="https://fonts.googleapis.com" />
this configuration is automated so you don't need to touch it. It's better to pre-render them using a plugin, since it's the power of Gatsby.
回答2:
You made a minor mistake.
It should be
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=TheFontYouWantToUse&display=swap />
If you do a forward slash as shown in your example it will result in a 404 not found, hence the console error. Replace it with a URL parameter (&
) and it should work fine.
@fontface
is just a way of loading a font from within a stylesheet.
For example within your main CSS file you could add the following and that would also load the font in. Notice the font-display
property set to swap
.
@font-face {
font-family: 'Pacifico';
font-style: normal;
font-weight: 400;
src: local('Pacifico Regular'), local('Pacifico-Regular'), url(https://fonts.gstatic.com/s/pacifico/v12/FwZY7-Qmy14u9lezJ-6H6MmBp0u-.woff2) format('woff2');
font-display: swap;
}
来源:https://stackoverflow.com/questions/62889585/pagespeed-insights-diagnostic-ensure-text-remains-visible-during-webfont-load