Created
October 23, 2019 23:49
-
-
Save blizzrdof77/cf117fea4f0ec31befbf651a2e90e4a9 to your computer and use it in GitHub Desktop.
Load CSS stylesheet or insert raw CSS dynamically with JavaScript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SDG = SDG || {}; | |
SDG.loadStyle = function(cssSource, append) { | |
var append = typeof append === 'undefined' ? true : append, | |
external = !(cssSource.indexOf('{') > 0 && cssSource.indexOf('}') > 1), | |
newElem = external ? ((function() { | |
i = document.createElement('link'); | |
i.rel = 'stylesheet'; | |
i.href = cssSource; | |
i.type = 'text/css'; | |
return i | |
})()) : ((function() { | |
i = document.createElement('style'); | |
i.type = 'text/css'; | |
i.innerHTML = cssSource; | |
return i; | |
})()); | |
var newCss = append ? document.querySelectorAll('html > * link:last-of-type,html > * style:last-of-type') : document.querySelectorAll('html > * link:first-of-type,html > * style:first-of-type'); | |
newCss = ((newCss.length > 0) ? (append ? newCss[newCss.length - 1] : newCss[0]) : (append ? document.querySelector('body > *:last-child') : document.querySelector('head > *:first-child'))); | |
newCss.insertAdjacentElement((append ? 'afterend' : 'beforebegin'), newElem); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment