swordfish
swordfish

Reputation: 149

Moving unobtrusive javascript out of html.erb file

I have a html.erb file in one of my views. The file is pretty big and has about 2/3 javascript code and just 1/3 html. I dont like this file being too cluttered. The javascript part is mostly event handlers and usage of jquery UI components like date pickers, dialogs etc for the corresponding html elements in the page. I would like to separate the javascript part from the html part.

  1. Can I move the javascript to a separate js.erb file and use it like a partial? What is the advantage of this?

  2. How would I move the javascript to a static .js file when I use rails API like I18n.() and <%= form_authenticity_token %>. Should I pass them every time to the wrapping javascript function? Is there a better way to do this?

  3. If I move javascript out of the html.erb file will it help in caching/rendering of html.erb page?

Interested to find out if there are any re-usable patterns

Sample code on the html.erb file:

 <% content_for :javascript do %>
 <script type="text/javascript">

 $(document).ready(function() 
 {
     $('#create_segment_dialog').dialog({
            title: "<%= I18n.t("segment.create_segment_title") %>",

     // lots of javascript


 }

 </script>
 <%end %>

 //HTML starts here

 <div id="right-column">

Upvotes: 1

Views: 833

Answers (1)

mccannf
mccannf

Reputation: 16659

My 2c, but I know there are differing opinions on this:

Try and separate out as much of your JS code into a function or functions and put them into JS files in your asset pipeline. Take advantage of the move to break your JS into re-usable components that could be used by other methods/controllers.

This means you get all the benefits of the asset pipeline for the JS you move there:

  • Caching & fingerprinting your JS assets
  • Minification & compression support to save bandwidth
  • Minification to obfuscate your code if that is something you want
  • Concatenation of JS files to reduce the number of requests a browser has to make
  • Possibility to serve the assets from another location (CDN, web tier vs app tier)
  • Improved DRYness if that JavaScript is used by other methods/controllers

The drawback? As you've pointed out, any Rails variables have to be passed in as parameters to the functions.

Moving your JavaScript to a .js.erb partial is an option, but if this code is very specific to a particular method or controller then it is not necessarily improving DRYness - it may make your code a little more readable, by separating HTML and JS.

Upvotes: 3

Related Questions