Skip to content

Instantly share code, notes, and snippets.

@lsmith
Created March 20, 2009 22:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lsmith/82607 to your computer and use it in GitHub Desktop.
Save lsmith/82607 to your computer and use it in GitHub Desktop.
// Converts the content inside <script src="script2style.js">YOUR CSS</script>
// into a style block that will only be applied if js is turned on
(function () {
var d = document,
scripts = d.getElementsByTagName('script'),
me = scripts[scripts.length - 1],
head = d.getElementsByTagName('head')[0],
content = me.innerHTML.replace(/@import\((.*?)\);?/m,function (m,href) {
// IE crashes on link.rel = 'stylesheet' if the link is not attached
// to the head, so we can't use a DocumentFragment for an all-in-one
// replacement
link = head.appendChild(d.createElement('link'));
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = href.replace(/^[\s'"]*|[\s'"]*$/g,'');
return '';
}),
link,style;
if (/\S/m.test(content)) {
style = d.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = content;
} else {
style.appendChild(d.createTextNode(content));
}
head.appendChild(style);
}
me.parentNode.removeChild(me);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment