public
Last active

Dynamically changing favicons with JavaScript

  • Download Gist
change-favicon.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*!
* Dynamically changing favicons with JavaScript
* Works in all A-grade browsers except Safari and Internet Explorer
* Demo: http://mathiasbynens.be/demo/dynamic-favicons
*/
 
// HTML5™, baby! http://mathiasbynens.be/notes/document-head
document.head || (document.head = document.getElementsByTagName('head')[0]);
 
function changeFavicon(src) {
var link = document.createElement('link'),
oldLink = document.getElementById('dynamic-favicon');
link.id = 'dynamic-favicon';
link.rel = 'shortcut icon';
link.href = src;
if (oldLink) {
document.head.removeChild(oldLink);
}
document.head.appendChild(link);
}

Update: The Chrome bug was fixed in Chrome 6 (released Sep 10th, 2010), so the Chrome hack that broke the forward button isn’t really necessary anymore.

@mathiasbynens Minor nitpick: Line 8 should read document.head || (document.head = document.getElementsByTagName('head')[0]);. Omitting the parentheses produces a syntax error.

@kitgoncharov That’s not a nitpick at all, just a silly typo on my end. Thanks!

@mathiasbynens No problem!

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.