Faffing with Favicons

13th July 2019

Favicons are a neat way to add an extra request to your webpage. It kept irritating me that for every request, in addition to my css and js, one had to request a favicon in equal size, which would only load once all other requests had finished.

This can be seen from the Developer Console in most browsers within the Network details. Favicon's - even with http 2.0 - load after everything else, and this is clearly the number one priority.

I found a helpful StackOverflow post which adequately explained this. Simply get the base64 representation of your image:

$ cat img | base64
AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAQAQAAAAAAAAAAAAAAAAA
AAAAAADXuJr/17ia/9e4mv/XuJr/17ia/9e4mv/XuJr/17ia/9e4mv/XuJr/17ia/9e4mv/XuJr/
[ . . . snip . . . ]
17ia/9e4mv/XuJr/17ia/9e4mv/XuJr/17ia/9e4mv/XuJr/17ia/9e4mv/XuJr/17ia/9e4mv/X
uJr/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAA==

Then add the following within your JavaScript (remembering to add the backslashes after each line of base64) to automatically insert our new header:

var favIcon = "\
AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAQAQAAAAAAAAAAAAAAAAA\
AAAAAADXuJr/17ia/9e4mv/XuJr/17ia/9e4mv/XuJr/17ia/9e4mv/XuJr/17ia/9e4mv/XuJr/\
[ . . . snip . . . ]
17ia/9e4mv/XuJr/17ia/9e4mv/XuJr/17ia/9e4mv/XuJr/17ia/9e4mv/XuJr/17ia/9e4mv/X\
uJr/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\
AAAAAAAAAAAAAA==";

var docHead = document.getElementsByTagName('head')[0];
var newLink = document.createElement('link');
newLink.rel = 'shortcut icon';
newLink.type = 'image/x-icon';
newLink.href = 'data:image/png;base64,'+favIcon;
docHead.appendChild(newLink);

Finally, for neatness sake add an empty shortcut icon within your header at the top of each and every html page, to instruct the browser to not bother fetching a favicon before it loads the js.

<html>
 <head>
  <link rel="shortcut icon" type="image/x-icon" href="data:image/png;,"/>
  [ . . . snip . . . ]
 </head>
[ . . . snip . . . ]
</html>