I have a rails application where I am trying to have jQuery render WITH an HTML file. The point of this is that the jQuery is specific to the page so I don't want it loading for every page by putting it in the header. Here's what I have done to the files
# GET /messages/new
@message = Message.new
@users = User.where('id != ' + current_user.id.to_s)
respond_to do |format|
format.html # new.html.erb
<div class="large-12 columns">
<%= render 'form' %>
<%= link_to 'Back', messages_path, :class => "button small" %>
$("h1").html('hello'); //for testing that it works
I don't think your method is a particularly standard way to accomplish what you want. The reason why your JS template is not being loaded is because your controller is setup to respond with an HTML template, if the browser requests HTML, and a JS template, if the browser requests JS. It will never return both because the browser can only request one or the other.
In other words, the respond_to block in your controller is instructing the controller how to respond to requests for different types of content, not listing all of the types of content that will be sent, on every request.
There are a couple of things to consider here. Firstly, just because JS is not used on a particular page, is not, in itself, a good reason not to load it. Rails, via Sprockets, will concatenate and minify all of your JS into a single file. As long as this file does not change, then it will be cached by a user's browser. This will result in a faster response when your user visits a page that does require this JS, as it won't need to make an extra request in order to get the new JS.
If you are concerned about your JS running on content that it shouldn't, then you should really be guarding against this by adding a unique identifier to the page, or pages, on which you want it to run, then detecting that identifier in your JS. For example:
However, there are some circumstances in which it might be beneficial to load JS separately. The best way to accomplish that, in my opinion, is to have a content for block that appends content to your head, if an individual view needs it.
So in your application layout:
messages_new.js will then only included, and therefore run, on views where you include that content_for block. It should not appear on any other page.
Alternatively, if you don't care if the JS is loaded last, then you can just add the include helper at the bottom of the new.html.erb: