Skip to content

Instantly share code, notes, and snippets.

@kirbysayshi
Created August 30, 2011 19:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kirbysayshi/1181731 to your computer and use it in GitHub Desktop.
Save kirbysayshi/1181731 to your computer and use it in GitHub Desktop.
quick node script to inline a css stylesheet into html
#!/usr/bin/env node
var fs = require('fs')
,jsdom = require('jsdom')
,cssom = require('cssom')
,request = require('request')
,style = fs.readFileSync('./styles.css', 'utf8')
,tpls = [
'tpl_content/another_template.html'
,'tpl_content/another_template.html'
]
,outputDir = '_tpl_inlined'
,styles = cssom.parse( style )
,jqueryStr;
function inlineAll(){
tpls.forEach(function(el, i){
jsdom.env({
html: fs.readFileSync(el, 'utf8')
,src: [jqueryStr]
,done: function(errors, window){
var i, j, rule, prop, val, inlined, outPath
for(i = 0; i < styles.cssRules.length; i++){
rule = styles.cssRules[i]
for(j = 0; j < rule.style.length; j++){
prop = rule.style[j];
val = rule.style[prop];
window.$( rule.selectorText ).css(prop, val);
}
}
inlined = window.$('body').html();
// prevent crap like {include &quot;header&quot;}
inlined = inlined.replace(/\{(\S*)\s&quot;(.*?)&quot;\}/gi, function(substr, m1, m2, offset, s){
//console.log(arguments);
return '{' + m1 + ' ' + '"' + m2 + '"}';
})
outPath = outputDir + '/' + el.split('/').pop();
fs.writeFileSync(outPath, inlined)
console.log('inlined', outPath);
}
})
});
}
request('http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js', function(err, response, body){
if (!err && response.statusCode == 200) {
jqueryStr = body;
inlineAll();
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment