Rails Javascript压缩/缩小对respond_to javascript响应? [英] Rails Javascript compression/minification on respond_to javascript response?

查看:133
本文介绍了Rails Javascript压缩/缩小对respond_to javascript响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问候Rails和Javascript专家!

Greetings Rails and Javascript Gurus!

我有一个项目,我在返回一个大的javascript文件

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

respond_to do |format|
   format.js
end

block。

我试图找出如何缩小或压缩.js响应,因为.js.erb视图充满了注释,并且根据控制器的结果大小不一。

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?

推荐答案

好吧,也许我有一个解决方案:

well, maybe I have a solution:

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

这完美有效。当然关键是 minify 方法。你会发现很多JS minifiers。例如,你可以使用这个(如果许可证允许): http ://github.com/thumblemonks/smurf/raw/master/lib/smurf/javascript.rb - 它基于Crockford的jsmin.c。

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.

如果你把这个文件放到lib中,需要它,你的minify方法可能如下所示:

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

希望它对你有所帮助。

如果你计划自动缩小,那么你可能应该选择一块中间件。令人惊讶的是我找不到任何东西(有很多针对CSS / JS,但它是关于静态资产而不是动态内容),但编写它不会是一个问题。

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.

这篇关于Rails Javascript压缩/缩小对respond_to javascript响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆