Load SDG icons in SVG when available
SVG files are smaller than PNG files, can be compressed, and are scalable. We're choosing to render SVG files as images instead of inline because inline SVGs aren't cached nor compressed, and they might appear several times on the same page, making the generated HTML much larger. We could also load them with an SVG sprite, using `<use>`, which would reduce the number of HTTP requests when several icons are present on the page (like in the index of most sections). However, using SVG inside an `<img>` tag is universally supported, while the `<use>` tag doesn't work in Internet Explorer when using an external URI and support in Opera Mini and UC Browser is unknown.
This commit is contained in:
@@ -7,7 +7,11 @@ class SDG::Goals::IconComponent < ApplicationComponent
|
||||
end
|
||||
|
||||
def image_path
|
||||
"sdg/#{locale}/goal_#{code}.png"
|
||||
if svg_available?
|
||||
svg_path(locale)
|
||||
else
|
||||
png_path(locale)
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
@@ -17,8 +21,25 @@ class SDG::Goals::IconComponent < ApplicationComponent
|
||||
end
|
||||
|
||||
def locale
|
||||
[*I18n.fallbacks[I18n.locale], "default"].find do |fallback|
|
||||
AssetFinder.find_asset("sdg/#{fallback}/goal_#{code}.png")
|
||||
@locale ||= [*I18n.fallbacks[I18n.locale], "default"].find do |fallback|
|
||||
AssetFinder.find_asset(svg_path(fallback)) ||
|
||||
AssetFinder.find_asset(png_path(fallback))
|
||||
end
|
||||
end
|
||||
|
||||
def svg_available?
|
||||
AssetFinder.find_asset(svg_path(locale))
|
||||
end
|
||||
|
||||
def svg_path(locale)
|
||||
"#{base_path(locale)}.svg"
|
||||
end
|
||||
|
||||
def png_path(locale)
|
||||
"#{base_path(locale)}.png"
|
||||
end
|
||||
|
||||
def base_path(locale)
|
||||
"sdg/#{locale}/goal_#{code}"
|
||||
end
|
||||
end
|
||||
|
||||
@@ -17,5 +17,6 @@ Rails.application.config.assets.precompile += %w[print.css]
|
||||
Rails.application.config.assets.precompile += %w[pdf_fonts.css]
|
||||
Rails.application.config.assets.precompile += %w[sdg/*.png]
|
||||
Rails.application.config.assets.precompile += %w[sdg/**/*.png]
|
||||
Rails.application.config.assets.precompile += %w[sdg/**/*.svg]
|
||||
|
||||
# Loads custom images and custom fonts before app/assets/images and app/assets/fonts
|
||||
|
||||
Reference in New Issue
Block a user