ZwiiCMS/core/vendor/favicon-switcher/favicon-switcher.js

67 lines
1.5 KiB
JavaScript
Raw Normal View History

2021-12-01 16:07:42 +01:00
// FavIcon Switcher V1.2.2
2020-09-19 17:35:02 +02:00
;(function(mod){
2021-12-01 16:07:42 +01:00
function collectLinks() {
return Array.prototype.slice.apply(
document.head.querySelectorAll('link[rel*="icon"]')
)
}
function applyLink(source, target) {
target.setAttribute('type', source.getAttribute('type'))
target.setAttribute('href', source.getAttribute('href'))
}
// eslint-disable-next-line no-unused-vars
function initSwitcher(delay) {
// Exit if media queries aren't supported
if (typeof window.matchMedia !== 'function') {
return function noop() {}
2020-09-19 17:35:02 +02:00
}
2021-12-01 16:07:42 +01:00
var links = collectLinks()
var current = document.createElement('link')
var prevMatch
current.setAttribute('rel', 'shortcut icon')
document.head.appendChild(current)
function faviconApplyLoop() {
var matched
links.forEach(function(link) {
if (window.matchMedia(link.media).matches) {
matched = link
}
})
if (! matched) {
return
2020-09-19 17:35:02 +02:00
}
2021-12-01 16:07:42 +01:00
if (matched.media !== prevMatch) {
prevMatch = matched.media
applyLink(matched, current)
2020-09-19 17:35:02 +02:00
}
2021-12-01 16:07:42 +01:00
}
var intervalId = setInterval(faviconApplyLoop, delay || 300)
function unsubscribe() {
clearInterval(intervalId)
2020-09-19 17:35:02 +02:00
links.forEach(function(link) {
2021-12-01 16:07:42 +01:00
document.head.appendChild(link)
2020-09-19 17:35:02 +02:00
})
}
2021-12-01 16:07:42 +01:00
faviconApplyLoop()
links.forEach(function(link) {
document.head.removeChild(link)
})
return unsubscribe
}
initSwitcher()
})()