Skip to content

Instantly share code, notes, and snippets.

@mipearson
Created July 12, 2013 04:24
Show Gist options
  • Save mipearson/5981422 to your computer and use it in GitHub Desktop.
Save mipearson/5981422 to your computer and use it in GitHub Desktop.
Helper & Rake task for SVG fallback usage & generation. Assumes Rails w/asset pipeline, your svgs are all in app/assets/images/vector, and imagemagick & optipng are installed.
module AssetsHelper
# SVG with PNG fallback for IE8.
# Run rake app:svg_fallback to generate fallbacks
def svg_image_tag source, *args
options = args.extract_options!
svg_class = options.fetch(:class, '')
svg_class += ' svg'
content = image_tag "vector/" + source, *args, options.merge(class: svg_class)
content << "\n<!--[if lt IE 9]>\n".html_safe
content << image_tag("vector/fallback/" + source.gsub('.svg', '.png'), *args, options)
content << "\n<![endif]-->\n".html_safe
content
end
end
namespace :app do
task :svg_fallback do
desc "Create fallback images for SVGs in app/assets/vector"
vector_dir = Rails.root.join(*%w{app assets images vector})
fallback_dir = vector_dir.join('fallback')
Dir[vector_dir.join('**/*.svg')].each do |path|
path = Pathname.new(path)
file = path.relative_path_from(vector_dir)
destination = fallback_dir.join(file)
FileUtils.mkdir_p destination.dirname
destination = destination.to_s.gsub(".svg", ".png")
puts "Converting #{file}"
system "convert -background none #{path} #{destination}"
puts "Optimising .png with optipng"
system "optipng --quiet #{destination}"
end
end
end
@mipearson
Copy link
Author

.. also worth mentioning that we have CSS that hides .svg in IE8

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