Skip to content

Instantly share code, notes, and snippets.

@lapo-luchini
Forked from mathiasbynens/change-favicon.js
Last active May 4, 2021 03:07
Show Gist options
  • Save lapo-luchini/303a64f25503a2ebc2b4 to your computer and use it in GitHub Desktop.
Save lapo-luchini/303a64f25503a2ebc2b4 to your computer and use it in GitHub Desktop.
Dynamically change favicon from CSS. (does not work on Internet Explorer and Safari)
/*! dynamically change favicon from CSS (does not work on Internet Explorer and Safari)
*
* use with:
* <link id='linkCSS' href='my.css' type='text/css' rel='stylesheet' />
* <link id='favicon' rel="shortcut icon" href="../images/favicon.png" type="image/png" />
*
* my.css can contain:
* #favicon { background-image: url(any valid URL); }
*/
(function () {
var rules = document.getElementById('linkCSS').sheet.cssRules;
for (var i = 0; i < rules.length; ++i) {
if (rules[i].selectorText != '#favicon')
continue;
var m = /url[(]['"]?([^'")]+)['"]?[)]/.exec(rules[i].cssText);
if (m) {
var old = document.getElementById('favicon'),
link = document.createElement('link');
link.id = old.id;
link.rel = old.rel;
link.href = m[1];
old.parentNode.replaceChild(link, old);
return;
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment