Kilian Valkhof

Front-end developer, user experience designer & Jedi.

The case of the disappearing favicon

Javascript, 23 August 2010, 8 comments

Firefox has an annoying bug: If you set the window.location.hash, your favicon disappears. Very annoying. The bug has been open and confirmed for a long time, and Firefox 3.0 all the way to 3.6 are affected. But it hasn’t been fixed yet, so here’s how to fix it yourself.

I encountered this bug while building Lystener. I change the location hash there quite often, and each time I did, the favicon would disappear. Finding the root cause took me quite a while, and apart from the bug report I could not find any page describing why this happens and what to do about it. So I figured that I’d write a quick post about it to make it Google-able at least.

Luckily, there is an easy fix: Just reset the favicon after changing the window.location.hash. Here’s a jQuery function that does just that:

function setFavicon() {
  var link = $('link[type=image/x-icon]').remove().attr("href");
  $('<link href="'+ link +'" rel="shortcut icon" type="image/x-icon" />').appendTo('head');
}

It’s fairly straightforward: We find the current <link> referencing the favicon, remove it, and then, making use of jQuery’s standard of functions returning themselves, get the href attribute of the just-deleted link. Then we simply set that as the href in a newly created link element, and add that to the head.

Just execute that function each time you change the window.location.hash, and you’re all set!

Thank you for reading this article.

Please don't hesitate to leave a comment!

I am a front-end developer and user experience developer from the Netherlands, and you can hire me. Contact me or ping me on twitter: @kilianvalkhof.

8 comments

  1. Anders Eurenius 23 August 2010, 15:52

    Hey! Can we use this together with data urls to animate it?

  2. You can, there are entire libraries for it: Favicon.js. They’re overkill for this problem though, which is why I opted for a two-liner.

  3. Anders Eurenius 23 August 2010, 16:12

    Yeah, I just noticed. (I built it and tried it.) Thanks for the link though, will check!

  4. Kevin Fairchild 23 August 2010, 17:36

    Nice. That has bugged me for a while now.

  5. Thank you! You just save me to ask in stackoverflow :)

  6. THANK YOU!!!!!!!

    this display bug has been nagging me for months! i used a 960grid template system, and once integrated lost my favicon! with this little function, IT’S BACK!!!

    thank you, thank you, thank you!!! :)

    soon will be able to push this new code live, with your helpful function …

  7. This fixes the problem in FF, but seems to break it in IE8. Strangely, the symptoms in IE8 are identical to those in FF without the code :/ Wrapped it in if ($.browser.msie != true) seems to work.

  8. Thanks a lot!

Your response?

If you post code examples, make sure to escape your HTML.