2

sprockets does all the minification for js assets, but a lot of javascript is written in a respond_to :js UJS responses.

Making the javascript readable while programming also makes it bloated with useless data that the browser doesn't need while processing them (like readable variable names and spaces)

Is there a way to automatically minify/uglify UJS responses so they will remain readable while programming but will be minified when sent to the browser? (minifying the source is not an option)

Nick Ginanto
  • 31,090
  • 47
  • 134
  • 244

1 Answers1

0

First, what you're talking about isn't necessarily UJS, but rather RJS or Ruby JavaScript, or javascript generated on-the-fly from ruby templates.

UJS, very (most?) often, is not done via dynamic javascript, but by returning dynamic data which is then manipulated by static javascript. This has many advantages; relevant to this case: it means that your javascript is already minified (and probably cached) client-side and you're just sending serialized data down the wire.

If you can, you might want to think about using that approach.

If you cannot, you might automagically minify your RJS actions with middleware, something like below (a raw pseudocoded version). But do so with care. You'll also want to consider whether the benefits of minification are worth the cost, e.g. the time/cost of minifying every request vs the time/cost of sending larger files to the client.

For more info on middleware, refer to the docs

module RJSMinifier
  def initialize(app)
    @app = app
  end

  def call(env)
    status, headers, response = @app.call(env)

    # pseudocode: if this is not an RJS request or the request did not
    # complete successfully, return without doing anything further
    if (this request is not RJS or status is not ok)
      return [status, headers, response]
    end

    # otherwise minify the response and set the new content-length
    response = minify(response)
    headers['Content-Length'] = response.length.to_s

    [status, headers, response]
  end

  def minify(js)
    # replace this with the real minifier you end up using
    YourMinifier.minify(js)
  end
end
Community
  • 1
  • 1
numbers1311407
  • 33,686
  • 9
  • 90
  • 92