Create a gist now

Instantly share code, notes, and snippets.

Dynamically changing favicons with JavaScript
/*!
* 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);
}
@mathiasbynens

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.

@kitcambridge

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

@mathiasbynens

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

@fritzweisshart

In order to avoid caching of the favicon, I added +'?='+Math.random()

function changeFavicon(src) {
src = src+'?='+Math.random(); // so wird das cachen zuverlässig vermieden
var link = document.createElement('link'),
oldLink = document.getElementById('dynamic-favicon');
link.id = 'dynamic-favicon';
link.rel = 'icon';
link.href = src;
if (oldLink) {
document.head.removeChild(oldLink);
}
document.head.appendChild(link);

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment