trickydiddy
trickydiddy

Reputation: 587

Loading JavaScript in view in Ruby on Rails

I want to use view specific JavaScript in Ruby on Rails 4.2.0 so I wanted to load it dynamically wherever I want to load it. I put the the javascript file which should be loaded(headers.js) in assets/javascripts. I removed the require tree line in the application.js file.

I have updated application.html.erb

application.html.erb

<!DOCTYPE html>
<html>
   <head>
      <title>Sandbox</title>
      <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
      <%= stylesheet_link_tag params[:controller] %>
      <%= csrf_meta_tags %>
      <%= render 'partials/shim' %>
   </head>
   <body>
      <%= render 'partials/header' %>
      <%= yield :javascript_includes %>
      <%= render 'partials/footer' %>
      <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
   </body>
</html>

and I wanted to call the javascript file on the very top of the view.

view.html.erb

<% content_for :javascript_includes do %>
  <%= javascript_include_tag "headers.js" %>
<% end %>

I have updated the initializers/assets.rb file as well:

Rails.application.config.assets.precompile += %w( headers.js )

For some reason the html content of the view will not load and I'm getting an error in the console: Uncaught ReferenceError: jQuery is not defined.

Why it does not work? How I can make this work and what am I missing?

Upvotes: 1

Views: 2608

Answers (2)

Ravi Teja Dandu
Ravi Teja Dandu

Reputation: 476

This should work:

Add in view

<% content_for(:head) do %>
  <%= javascript_include_tag 'headers.js' %>
<% end %>

And in initializers/assets.rb

Rails.application.config.assets.precompile += %w( headers.js )

Upvotes: 0

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33420

Instead passing javascript_includes to yield, try just requiring your needed javascript file wherever you want directly in the view, something like:

<%= javascript_include_tag "headers.js" %>
  <div class="vertical-center">
    ...

Your body in application.html.erb just like:

<%= render 'partials/header' %>
<%= yield %>
<%= render 'partials/footer' %>

And you could move the application.js file to the top, in order to preserve the Rails "structure":

<%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
...

Upvotes: 1

Related Questions