Skip to content

Instantly share code, notes, and snippets.

@glebm
Last active October 12, 2018 15:36
Show Gist options
  • Save glebm/6360088 to your computer and use it in GitHub Desktop.
Save glebm/6360088 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'base64'
require 'open-uri'
# file or url
def get_css(src)
if src.start_with? 'http'
src = src.gsub('|', '%7C')
STDERR.puts "# GET #{src}"
# simulate modern browser to get woff
open(src, 'User-Agent' => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36").read
else
STDERR.puts "Read #{src}"
File.read(src)
end
end
def inline_urls(css)
css.gsub! /url\((.*?)\.(\w+)\)/ do
ext = $2
url = "#{$1}.#{$2}"
STDERR.puts "# Found #{ext} font: #{url}"
mime = {
'woff' => 'application/font-woff'
}[ext] or raise "need mime type for #{ext}"
font_src = get_css(url)
base_64 = Base64.strict_encode64(font_src)
STDERR.puts "# font #{"was %.1fKB, now %.1fKB" % [font_src.bytesize / 1024.0, base_64.bytesize / 1024.0]}"
"url('data:#{mime};base64,#{base_64}')"
end
end
raise "please provide url or path, e.g https://fonts.googleapis.com/css?family=Arimo:400" unless ARGV[0]
puts inline_urls(get_css ARGV[0])
@glebm
Copy link
Author

glebm commented Aug 28, 2013

I've just written a post on CSS inlining http://blog.glebm.com/2013/08/28/inline-css-fonts.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment