预取的资源加载两次

Fra*_*bot 10 html prefetch

我想使用html预取来预取字体文件.我按照这里的建议:https://css-tricks.com/prefetching-preloading-prebrowsing/

<!doctype html>
<html>
<head>
<link rel="prefetch" href="https://fonts.gstatic.com/s/opensans/v13/cJZKeOuBrn4kERxqtaUH3ZBw1xU1rKptJj_0jans920.woff2">
<style>
@font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 400;
  src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/cJZKeOuBrn4kERxqtaUH3ZBw1xU1rKptJj_0jans920.woff2) format('woff2');
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}

html, body {
font-family: 'Open Sans';
}
</style>
</head>
<body>
Hello world
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

但是,字体文件实际上在Chrome上加载了两次.我没有尝试过其他浏览器.

结果

我做错了什么吗?

Fra*_*bot 10

这是一个不正确的用法prefetch.请参阅资源:https://www.smashingmagazine.com/2016/02/preload-what-is-it-good-for/

<link rel="prefetch">是一个指令,告诉浏览器获取下一个导航可能需要的资源.

...

<link rel="subresource">最初是计划解决当前的导航问题,但它没有以一些壮观的方式做到这一点.

...

您可以使用的基本方法preload尽早加载后期发现的资源.[...]有些资源隐藏在CSS和JavaScript中


所以,preload我们想在这里使用.但是,它几乎没有得到支持.

这篇文章还有一些关于加载字体的话:

就像是:

<link rel="preload" href="font.woff2" as="font" type="font/woff2" crossorigin>

值得一提的是:在获取字体时必须添加crossorigin属性,因为它们是使用匿名模式CORS获取的.是的,即使您的字体与页面的原点相同.抱歉.


将所有这些放在一起,更新的可重现代码如下所示:

style.css:

/* 2MB of random character comment fluff */

@font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 400;
  src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/cJZKeOuBrn4kERxqtaUH3ZBw1xU1rKptJj_0jans920.woff2) format('woff2');
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}

html, body {
font-family: 'Open Sans';
}
Run Code Online (Sandbox Code Playgroud)

index.html:

<!doctype html>
<html>
<head>
<link rel="preload" as="font" type="font/woff2" crossorigin href="https://fonts.gstatic.com/s/opensans/v13/cJZKeOuBrn4kERxqtaUH3ZBw1xU1rKptJj_0jans920.woff2">
<link rel="stylesheet" href="style.css">
</head>
<body>
Hello world
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

现在,它只适用于Chrome Canary.我指望即将推出更好的浏览器支持.

铬:

在此输入图像描述

加纳利:

在此输入图像描述