Reputation: 1469
For this particular rails project, I want to save on an http request, so I'd like to output all the javascript onto the body that has been in the rails asset pipeline.
Is there a way to do this in rails?
Upvotes: 2
Views: 108
Reputation: 33547
You unfortunately won't be able to get this working easily in development since the files are being served live by Sprocket's server, but getting this working in production is fairly simple: you just need to loop over the compiled scripts and render them in a blob.
Here's a helper that you can use instead of javascript_include_tag
which will do just that:
module ApplicationHelper
if Rails.env.production?
def embedded_javascript_include_tag(*sources)
options = sources.extract_options!.stringify_keys
scripts = sources.uniq.map { |source|
File.read("#{Rails.root}/public/#{javascript_path(source)}")
}.join("\n").html_safe
content_tag(:script, scripts, options)
end
else
def embedded_javascript_include_tag(*sources)
javascript_include_tag(sources)
end
end
end
Note you'll still need to run rake assets:precompile
for this to work. Don't forget to set the environment to enable any uglifiers and minifers! (RAILS_ENV=production rake assets:precompile
)
Upvotes: 2