每个人都知道如何在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请求。我们如何将其与我们的标志和其他艺术品一起放入现有的精灵图像中?
对@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
很抱歉,您不能将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请求。
正确的解决方案是使用HTTP管道。
HTTP管道是一种将多个HTTP请求写入到单个套接字而不等待相应响应的技术。只有HTTP/1.1支持管道,1.0中不支持。
它要求服务器支持它,但不一定参与其中。
HTTP管道需要客户端和服务器都支持它。符合HTTP/1.1的服务器需要支持流水线。这并不是说服务器必须通过管道处理响应,而是说如果客户端选择通过管道处理请求,服务器必须不会失败。
许多浏览器客户端在应该这样做的时候却没有这样做。
HTTP pipelining is disabled in most browsers.
Opera has pipelining enabled by default. It uses heuristics to control the level of pipelining employed depending on the connected server.
Internet Explorer 8 does not pipeline requests, due to concerns regarding buggy proxies and head-of-line blocking.
Mozilla browsers (such as Mozilla Firefox, SeaMonkey and Camino), support pipelining however it is disabled by default. It uses some heuristics, especially to turn pipelining off for IIS servers.
Konqueror 2.0 supports pipelining, but it's disabled by default.[citation needed]
Google Chrome does not support pipelining.
我建议你尝试在Firefox中启用管道,或者直接使用Opera(不寒而栗)。