Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails not serving compressed SVG files

I’ve been using Google PageSpeed to optimize my Rails 5.0 application, and something odd jumped out with SVGs in particular. I use Rack::Deflate to compress static assets like so...

config/application.rb

config.middleware.use Rack::Deflater

...and yet Google PageSpeed was nevertheless complaining about uncompressed SVGs being served.

I thought this was weird, so I added some code to manually compress SVGs as part of asset precompilation. This works perfectly, and I can go to http://myapp.com/sample_image.svg.gz and indeed I get the compressed image file.

However, Google PageSpeed is still complaining about uncompressed assets being served.

It would appear that, just like how Rails 5.0 wasn’t compressing my SVGs, when I compress them manually, it still won’t serve them.

Is there some kind of configuration I need to adjust here to get the compressed SVG files to be served correctly?

like image 566
isthmuses Avatar asked Dec 17 '25 12:12

isthmuses


2 Answers

I started a discussion about how to resolve this in a comprehensive way, since this also seems to affect font & json files that sprockets will compress but ActionDispatch::Static won't serve. Anyway, here's a solution via a monkeypatch (put in an initializer):

require 'action_dispatch/middleware/static'

ActionDispatch::FileHandler.class_eval do
  private

    def gzip_file_path(path)
      return false if ['image/png', 'image/jpeg', 'image/gif'].include? content_type(path)
      gzip_path = "#{path}.gz"
      if File.exist?(File.join(@root, ::Rack::Utils.unescape_path(gzip_path)))
        gzip_path
      else
        false
      end
    end
end
like image 102
swrobel Avatar answered Dec 19 '25 07:12

swrobel


This is still true for Rails 6.1. I've made a PR to fix this: https://github.com/rails/rails/pull/42407

like image 23
Georg Ledermann Avatar answered Dec 19 '25 06:12

Georg Ledermann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!