最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Rails Javascript compressionminification on respond_to javascript response? - Stack Overflow

programmeradmin9浏览0评论

Greetings Rails and Javascript Gurus!

I have a project where I am returning a large javascript file in a

respond_to do |format|
   format.js
end

block.

I am trying to figure out how I can minify or compress the .js response since the .js.erb view is full of comments and varies in size based on the results from the controller.

Anyone have any ideas?

Greetings Rails and Javascript Gurus!

I have a project where I am returning a large javascript file in a

respond_to do |format|
   format.js
end

block.

I am trying to figure out how I can minify or compress the .js response since the .js.erb view is full of comments and varies in size based on the results from the controller.

Anyone have any ideas?

Share Improve this question asked Sep 27, 2010 at 16:47 Dustin M.Dustin M. 2,9743 gold badges20 silver badges18 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 12

For Rails 4:

render js: Uglifier.new.compile(render_to_string)

well, maybe I have a solution:

respond_to do |format|
  format.js { self.response_body = minify(render_to_string) }
end

This perfectly works. Of course that the key is the minify method. You will find a lot of JS minifiers around. For example you can use this one (well if license permits): http://github.com/thumblemonks/smurf/raw/master/lib/smurf/javascript.rb - it is based on Crockford's jsmin.c.

If you put this file into your lib, require it, your minify method can look like this:

def minify(content)
  min = Smurf::Javascript.new(content)
  min.minified
end

Hope that it helped you.

If you plan to do minifying automatically then you probably should go for a piece of middleware. Surprisingly I was not able to find any (there are many aimed to the CSS/JS but it's about static assets not dynamic content) but it would not be such a problem to write it.

For rails 3 using the built in Uglifier method (the default for the assets pipeline)

See Radek's code above and just swap this in.

  def minify(content)
    Uglifier.new.compile(content)
  end
发布评论

评论列表(0)

  1. 暂无评论