每个人都知道如何在HTML中设置favicon.ico链接:
<link rel="shortcut icon" href="http://hi.org/icon.ico" type="image/x-icon">
但是对于一个只有几个字节的小图标,我们需要另一个可能会降低速度的HTTP请求,这是愚蠢的。
所以我想知道,我怎么能让favicon的一部分可用的精灵(例如,background-position=0px -200px;),可以作为一个logo在网站的其余部分,以加快网站的速度,并节省宝贵的和宝贵的HTTP请求。我们如何将其与我们的标志和其他艺术品一起放入现有的精灵图像中?
很抱歉,您不能将favicon与其他资源合并。
这意味着你基本上有两个选择:
If you're comfortable with your site not having a favicon - you can just have the href point to a non-icon resource that is already being loaded (e.g., a style sheet, script file, or even some resource that benefits from being pre-fetched).
(My brief testing indicates that this works across most, if not all, major browsers.)
Accept the extra HTTP request and just make sure your favicon file has aggressive HTTP cache-control headers set.
(If you have other websites under your control, you might even have them sneakily preload the favicon for this website - along with other static resources.)
附注:行不通的创造性解决方案:
奇怪的CSS数据URI技巧(由评论者Felix Geenen链接)不起作用。
使用JavaScript执行favicon <link>元素的延迟注入(由用户yc建议)可能只会让事情变得更糟——导致两个HTTP请求。
我在这个页面上找到了一个有趣的解决方案。它是用德语写的,但你应该能看懂代码。
您将图标的base64数据放入外部样式表中,因此它将被缓存。在你的网站头部,你必须定义带有id的favicon,并且favicon被设置为该id的样式表中的背景图像。
link#icon {
background-image:url("data:image/x-icon;base64,<base64_image_data>");
}
还有HTML
<html>
<head>
<link id="icon" rel="shortcut icon" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="/styles.css" />
...
</head>
<body>
...
</body>
</html>