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