Skip to content

Instantly share code, notes, and snippets.

@blizzrdof77
Created October 23, 2019 23:49
Show Gist options
  • Save blizzrdof77/cf117fea4f0ec31befbf651a2e90e4a9 to your computer and use it in GitHub Desktop.
Save blizzrdof77/cf117fea4f0ec31befbf651a2e90e4a9 to your computer and use it in GitHub Desktop.
Load CSS stylesheet or insert raw CSS dynamically with JavaScript.
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