title: Rails 4 - force browser to execute javascript response instead of displaying text
body: <p>I have a Rails 4 application where I need to force the controller to send a js response to all requests, html or js.  For some reason, the browser is displaying the response as text instead of executing the code when the controller receives an html request (for example, when the user makes a request by typing in the url).</p>
  
  <p><strong>Controller:</strong></p>
  
  <pre><code>def action
    render :template =&gt; 'sessions/home.js.erb', :content_type =&gt; "text/javascript"
  end
  </code></pre>
  
  <p><strong>sessions/home.js.erb:</strong></p>
  
  <pre><code>$("#button").on("click", function(){
    alert("got here");
  });
  </code></pre>
  
  <p>Instead of binding #button, the browser simply displays the code from home.js.erb as text.</p>
  
  <p>I've tried the following options in the controller but the results are the same - the browser just presents the text vs executing the code:</p>
  
  <pre><code>render js: "alert('got here')";
  </code></pre>
  
  <p>or</p>
  
  <pre><code>render :format =&gt; :js, :template =&gt; 'sessions/home.js.erb'
  </code></pre>
  
  <p>or</p>
  
  <pre><code>respond_to do |format|
     format.html {render :template =&gt; 'sessions/home.js.erb', :content_type =&gt; 'text/javascript'}
  end
  </code></pre>
  
  <p>or </p>
  
  <pre><code>respond_to do |format|
     format.html {render :template =&gt; 'sessions/home.js.erb', :content_type =&gt; 'application/javascript'}
  end
  </code></pre>
  
  <p>Can somebody help me figure out what I need to do in order to get the browser to execute the javascript?</p>