Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jonathantneal
Created November 15, 2011 05:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathantneal/1366249 to your computer and use it in GitHub Desktop.
Save jonathantneal/1366249 to your computer and use it in GitHub Desktop.
processStyle.js
(function (win, doc) {
var frag = doc.createDocumentFragment();
// expand css
function expandCSS(responseText, dirname) {
return responseText
// correct urls
.replace(/url\(['"]?(.+?)['"]?\)/g, 'url(' + dirname + '$1)')
// uncorrect behavior urls
.replace(/behavior:\s*url\((.*?)\)/g, function (url) { return url.replace(dirname, ''); })
// import imports
.replace(
/@import\s+url\((.+?)\);?/g,
function (all, url) {
var xhr = win.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('GET', url, false);
xhr.send(null);
return expandCSS(xhr.responseText, url.replace(/[^\/]+$/, ''));
}
);
}
// process style
win.processStyle = function (el, callback) {
el = doc.getElementById(el) || el;
// variables, i love variables
var
replaceElement = /link|style/i.test(el.nodeName);
styleEl = doc.createElement('style'),
expandedCSS = expandCSS(replaceElement ? el.href ? '@import url(' + el.href + ')' : el.innerHTML : el.attributes.style.nodeValue || el.style.cssText, '');
// process the expandedCSS
if (callback && callback.apply) expandedCSS = callback.apply(el, [expandedCSS]);
// if we're using the style attribute
if (!replaceElement) return el.setAttribute('style', expandedCSS);
// the style element can be tricky, best to let it think it belongs to a document, oh, and copy the media
frag.appendChild(styleEl).media = el.media;
// the style element can be tricky, best to set its content the way it wants
if (el.styleSheet) styleEl.styleSheet.cssText = expandedCSS; else styleEl.innerHTML = expandedCSS;
// replace the old with the new
el.parentNode.replaceChild(styleEl, el);
};
})(this, document);
(function (win, doc) {
function main(responseText) {
// macros storage var
var macros = {};
// modify response text
responseText = responseText
// strip comments
.replace(/\/\*[\W\w]*?\*\//g, '')
// get macros
.replace(
/@macros\s*\{([\W\w]*?)\}/g,
function (all, props) {
props.replace(
/([^\s]+?)\s*:\s*([^;]+?);/g,
function (all, nodeName, nodeValue) {
macros[nodeName] = nodeValue;
}
);
return '';
}
);
// replace macros
for (e in macros) while (responseText !== (responseText = responseText.replace(e, macros[e])));
// return modified response text
return responseText;
}
// process style macros
win.processStyleMacros = function (el) { processStyle(el, main); };
})(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment