我读了link preload documentation .在 html 的 head
部分,我有
<link rel="preload" href="/css/fonts/XRXV3I6Li01BKofINeaB.woff2" as="font">
稍后,我加载了一个 font.css
文件,其中加载了完全相同的字体文件(检查 url
):
@font-face {
font-family: 'Nunito';
font-style: normal;
font-weight: 400;
src: local('Nunito Regular'), local('Nunito-Regular'), url("/css/fonts/XRXV3I6Li01BKofINeaB.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
Chrome 上的错误?
但是 Chrome 控制台给出了警告
The resource https://autocosts.work/css/fonts/XRXV3I6Li01BKofINeaB.woff2 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.
事实上,浏览器加载了同一个文件两次(第 1 行和第 3 行指的是同一个文件)!
如何通过避免文件重复加载来使预加载工作?
最佳答案
我通过添加 type="font/woff2"crossorigin="anonymous"
<link rel="preload" href="/css/fonts/XRXV3I6Li01BKofINeaB.woff2" as="font" type="font/woff2" crossorigin="anonymous">
Fonts are indeed a special case
If you've got your sites' CORS settings worked out properly, you can successfully preload cross-origin resources as long as you set a crossorigin attribute on your element.
One interesting case in which this applies even if the fetch is not cross-origin is font files. Because of various reasons, these have to be fetched using anonymous mode CORS (see Font fetching requirements if you are interested in all the details).
关于html - 链接预加载不能避免字体加载重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54523445/