inline CSS in post-processing

This commit is contained in:
Sami Samhuri 2014-03-19 21:45:03 -07:00
parent 25482dd76c
commit 62159d17cb
7 changed files with 77 additions and 3 deletions

View file

@ -4,3 +4,5 @@ gem 'builder'
gem 'json'
gem 'mustache'
gem 'rdiscount'
gem 'nokogiri'
gem 'css_parser'

View file

@ -1,9 +1,15 @@
GEM
remote: https://rubygems.org/
specs:
addressable (2.3.5)
builder (3.0.0)
css_parser (1.3.5)
addressable
json (1.6.1)
mini_portile (0.5.2)
mustache (0.99.4)
nokogiri (1.6.1)
mini_portile (~> 0.5.0)
rdiscount (1.6.8)
PLATFORMS
@ -11,6 +17,8 @@ PLATFORMS
DEPENDENCIES
builder
css_parser
json
mustache
nokogiri
rdiscount

View file

@ -18,6 +18,9 @@ function main() {
echo "* munge html files to make them available without an extension"
munge_html
echo "* inline CSS"
$DIR/inline-css.rb "$TARGET"
echo "* minify js"
minify_js
}

53
bin/inline-css.rb Executable file
View file

@ -0,0 +1,53 @@
#!/usr/bin/env ruby -w -rrubygems
require 'bundler/setup'
require 'nokogiri'
require 'css_parser'
# Styles are so small, inline them all.
def main
root_dir = ARGV.shift
CSSInliner.new(root_dir).inline_all_css
end
class CSSInliner
def initialize(root_dir)
@root_dir = root_dir
end
def inline_all_css
Dir[File.join(@root_dir, '**/*.html')].each do |html_path|
next if html_path =~ /\/Chalk\/|\/tweets\//
inline_css(html_path)
end
end
def inline_css(html_path)
html = File.read(html_path)
doc = Nokogiri::HTML.parse(html)
css_parser = CssParser::Parser.new
doc.css('link').each do |link|
if link['rel'] == 'stylesheet'
path = File.join(@root_dir, link['href'])
css = File.read(path)
css_parser.add_block!(css)
style_node = Nokogiri::HTML.parse("
<style>
#{css}
</style>
").css('style')
link.replace(style_node)
end
end
File.open(html_path, 'w') { |f| f.puts(doc.to_html) }
end
end
main if $0 == __FILE__

View file

@ -1,8 +1,7 @@
#!/usr/bin/env ruby
#!/usr/bin/env ruby -w -rrubygems
# encoding: utf-8
require 'time'
require 'rubygems'
require 'bundler/setup'
require 'builder'
require 'json'

View file

@ -3,7 +3,6 @@
"subtitle": "words mean things",
"url": "http://samhuri.net",
"styles": [
"/css/font-awesome.min.css",
"/css/normalize.css",
"/css/style.css"
],

View file

@ -132,6 +132,16 @@
&copy; 2006 - <%= new Date().getFullYear() %> <a href="/about"><%= author %></a>
</footer>
<script type="text/javascript">
(function() {
var css = document.createElement('link');
css.href = '//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css';
css.rel = 'stylesheet';
css.type = 'text/css';
document.getElementsByTagName('head')[0].appendChild(css);
})();
</script>
<% for (var i in allScripts) { -%>
<script defer src="<%= allScripts[i] %>"></script>
<% } -%>