From 78811f5f4d2f5e8047fa8fc95c2c2ff8adbce9f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javi=20Mart=C3=ADn?= Date: Fri, 18 Jun 2021 13:40:55 +0200 Subject: [PATCH] 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 ``, 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 `` tag is universally supported, while the `` tag doesn't work in Internet Explorer when using an external URI and support in Opera Mini and UC Browser is unknown. --- app/components/sdg/goals/icon_component.rb | 27 +++++++++++++++++++--- config/initializers/assets.rb | 1 + 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/app/components/sdg/goals/icon_component.rb b/app/components/sdg/goals/icon_component.rb index 588da444f..496021afd 100644 --- a/app/components/sdg/goals/icon_component.rb +++ b/app/components/sdg/goals/icon_component.rb @@ -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 diff --git a/config/initializers/assets.rb b/config/initializers/assets.rb index 6630e63f6..6904fc4d7 100644 --- a/config/initializers/assets.rb +++ b/config/initializers/assets.rb @@ -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