sprockets 对 js 资产进行了所有的缩小,但是很多 javascript 是用respond_to :js
UJS 响应编写的。
在编程时使 javascript 可读也使得它在处理它们时被浏览器不需要的无用数据(如可读的变量名和空格)膨胀
有没有办法自动缩小/丑化 UJS 响应,以便它们在编程时保持可读性,但在发送到浏览器时会被缩小?(缩小来源不是一种选择)
sprockets 对 js 资产进行了所有的缩小,但是很多 javascript 是用respond_to :js
UJS 响应编写的。
在编程时使 javascript 可读也使得它在处理它们时被浏览器不需要的无用数据(如可读的变量名和空格)膨胀
有没有办法自动缩小/丑化 UJS 响应,以便它们在编程时保持可读性,但在发送到浏览器时会被缩小?(缩小来源不是一种选择)
首先,您所说的不一定是 UJS,而是RJS 或 Ruby JavaScript或从 ruby 模板动态生成的 javascript。
UJS,非常(大多数?)通常不是通过动态 javascript 完成的,而是通过返回动态数据,然后由静态 javascript 操作。这有很多优点;与这种情况相关:这意味着您的 javascript 已经在客户端进行了缩小(并且可能已缓存),并且您只是通过网络发送序列化数据。
如果可以,您可能需要考虑使用这种方法。
如果不能,您可以使用中间件自动缩小您的 RJS 操作,如下所示(原始伪代码版本)。但要小心。您还需要考虑缩小的好处是否值得付出代价,例如缩小每个请求的时间/成本与向客户端发送较大文件的时间/成本。
有关中间件的更多信息,请参阅文档
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