Sam Sam - 2 months ago 14
CSS Question

Isn't it silly that a tiny favicon requires yet another HTTP request? How to make favicon go into a sprite?

Everybody knows how to setup a favicon.ico link in HTML:

<link rel="shortcut icon" href="http://hi.org/icon.ico" type="image/x-icon" />


But I think it is just silly that for a tiny several-byte icon you need yet another HTTP request. So I wondered, how could I make that image part of a sprite (e.g. background-position=0px -200px;) in order to speed up and save that valuable HTTP request: how could I tackle this and get it into the rest of my existing image sprite with my logo and my other artworks?

The robot pointing to
favicon.ico
, item nr.31 on the waterfall graph, is my pet ZAM, he's often happier and he has a good point letting me know its time for some creative upgrades on the web, though he and I don't agree on his outfit, which I think is a bit silly today...


enter image description here

Answer

A minor improvement to @yc's answer is injecting the base64-encoded favicon from a JavaScript file that would normally be used and cached anyway, and also suppressing the standard browser behavior of requesting favicon.ico by feeding it a data URI in the relevant meta tag.

This technique avoids the extra http request and is confirmed to work in recent versions of Chrome, Firefox and Opera on Windows 7. However it doesn't appear to work in Internet Explorer 9 at least.

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 JS would normally be in here too. */

Demo: turi.co/up/favicon.html

Comments