Search code examples
javascriptruby-on-railsasset-pipeline

My Rails app is crashing because it's loading every JavaScript file, including ones that aren't related to the page being loaded


I'm diving into Ruby on Rails and I'm building an app that uses Rails 3.2.8. I'm still learning to use the Asset Pipeline, but I'm already running into a problem. I have my Javascript files organized and named by the different pages in my website (i.e. home.html -> home.js, parts.html -> parts.js), but my Rails app is loading all my Javascript files and one of my Javascript files is crashing because it's referencing elements that don't exist on the page that's loaded (home.html)...

"uncaught exception: jsobj.edit can't find div #parts_list"

Following the online documentation, I'm including in the manifest all the JS files that are needed in my app...

//= require modernizr-latest
//= require jquery
//= require jquery_ujs
//= require home
//= require parts
//= require_tree .

...so when I load the home page, the parts.js files is loaded and executed and crashing since the parts_list div doesn't exist on the homepage.

My questions are...

  1. Should I attempt to address this problem at the Javascript level? If so, how?
  2. Or should I attempt to fix it at the Rails level and only include Javascript files that should be running at any given time. Again, if so, how can I approach this?
  3. This seems like this would be a fairly common problem. Am I'm not using Rails correctly?

Thanks so much in advance for your wisdom!


Solution

  • To include specific javascript files into specific view pages only, you need to go with the following procedure.

    i) In the assets folder create a separate folder eg. 'separate_view' , and inside put your specific js, and css files.

    ii) In the application lay out write like following for 'separate_view'.
      <%= yield :separate_view %>

    iii) In your target template write the following for 'separate_view'.
      <% content_for (:separate_view) do %>
        <%= javascript_include_tag "xxx.js" %>
        <%= stylesheet_link_tag "xxx.css" %>
      <%end%>


    The above will go fine with your specific view files.