Is it possible to render a js file with Rails and minify the output?
Asked Answered
U

3

7

I'm generating some js output for each user using a template named example.js.erb. This is basically a javascript file where I have to put in the user's unique details. I'm using this inside of a widget for the user.

Is there any way to minify the js as it's being rendered? Right now the javascript is being rendered correctly, but it's in it's long form and I'd like to minify the output in order to reduce file size and increase download speed.

Underpart answered 11/11, 2011 at 20:3 Comment(4)
Are you sure you will gain in overall timings by making this kind of action?You will surely gain in network traffic, but you will also surely lose in computing time...Subset
These files will be heavily cached on the fronted by varnish which means they will be generated once, and served by varnish until a user changes it. So, yes, I think it's worth the compute time.Underpart
#3806451Cauline
Guess I was searching for the wrong thing. That link answers my question perfectly. Thanks.Underpart
U
4

Rails Javascript compression/minification on respond_to javascript response?

respond_to do |format|
  format.js { self.response_body = minify(render_to_string) }
end
Underpart answered 27/12, 2011 at 19:49 Comment(0)
B
0

Try something like this, in your controller:

def action_name
  js_code = render_to_string 'your_js_code_view'
  js_code.gsub!(/\r\n|\r|\n/, '') #and/or any other minimization you like
  render 'the_view_wich_will_show_the_minimized_js_code'
end
Bourke answered 11/11, 2011 at 23:14 Comment(0)
H
0

For Rails 4:

render js: Uglifier.new.compile(render_to_string)

For Rails 5:

render js: Uglifier.new(harmony: true).compile(render_to_string)
Hadik answered 28/3, 2019 at 4:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.