Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one minify a javascript partial within a rails erb file?

The application is not using the standard asset pipeline due to having some of the javascript being rendered dynamically by controller variables.

I'd like to minify the js before appending/inline-ing it into the html file that it would be served out from.

I've tried <render :partial => 'javascript.js'> which is the standard way to render a partial in an erb.

Ideally i'd just be able to do <render :partial => Minify.new.minify('javascript.js')> to render out a minified version of the js

like image 650
BOverflow Avatar asked Jan 29 '13 16:01

BOverflow


People also ask

How do you minify a JavaScript file?

To minify JavaScript, try UglifyJS. The Closure Compiler is also very effective. You can create a build process that uses these tools to minify and rename the development files and save them to a production directory.

How does Minify JavaScript work?

How Minification Works. Minification works by analyzing and rewriting the text-based parts of a website to reduce its overall file size. Minification extends to scripts, style sheets, and other components that the web browser uses to render the site. Minification is performed on the web server before a response is sent ...

Should you minify JavaScript?

It is important to minify your CSS and minimise JavaScript files so they can load faster on your web pages. There are many reasons why you should minify your CSS and JavaScript: Reduce file size: The more code there is in a file, the larger it will be. Minified code is usually much smaller than the original version.

Why do we need to minify JavaScript?

Minification is the process of minimizing code and markup in your web pages and script files. It's one of the main methods used to reduce load times and bandwidth usage on websites. Minification dramatically improves site speed and accessibility, directly translating into a better user experience.


1 Answers

You can try the uglifier gem (http://rubygems.org/gems/uglifier), I don't know about the performance, but you can do something like:

<script type="text/javascript">
  <%= raw Uglifier.new.compile(render "your_js_in_a_partial.js") %>
<script>
like image 83
Lucas Marcondes Pavelski Avatar answered Sep 24 '22 02:09

Lucas Marcondes Pavelski