每个人都知道如何在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请求。
对@yc的回答的一个小改进是从通常使用和缓存的JavaScript文件中注入base64编码的favicon,并通过在相关元标记中提供数据URI来抑制请求favicon.ico的标准浏览器行为。
这项技术避免了额外的http请求,并且被证实适用于Windows 7上最新版本的Chrome、Firefox和Opera。然而,至少在ie9中它似乎不能工作。
文件index . html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- Suppress browser request for favicon.ico -->
<link rel="shortcut icon"type="image/x-icon" href="data:image/x-icon;,">
<script src="script.js"></script>
...
文件script.js
var favIcon = "\
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABrUlEQVR42mNkwAOepOgxMTD9mwhk\
[...truncated for brevity...]
IALgNIBUQBUDAFi2whGNUZ3eAAAAAElFTkSuQmCC";
var docHead = document.getElementsByTagName('head')[0];
var newLink = document.createElement('link');
newLink.rel = 'shortcut icon';
newLink.href = 'data:image/png;base64,'+favIcon;
docHead.appendChild(newLink);
/* Other JavaScript code would normally be in here too. */
演示:turi.co / / favicon.html
这并不是对这个问题的真正回答,而只是对Marcel和yahelc给出的答案的赞扬。我为404图标问题提供了一个优雅的解决方案。
一些应用程序和浏览器会检查favicon.ico文件,如果在站点根目录中没有找到图标,您可以简单地用204响应头响应请求。
Apache的例子:
Apache选项一(也是我最喜欢的),在你的.htacces或.conf中简单的一行代码:
Redirect 204 /favicon.ico
Apache选项二:
<Files "favicon.ico">
ErrorDocument 204 ""
</Files>
Stoyan Stefanov写了一篇不错的博客文章供进一步阅读。