1

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?

2
  • 1
    Maybe your file depends on jQuery, and you're trying to load it before Rails loads jQuery, you'll need to see if changing the order of assets make it work. Commented Jul 29, 2017 at 21:17
  • Try just <%= javascript_include_tag "headers.js" %> and restart your server, what do you get? Commented Jul 29, 2017 at 21:27

2 Answers 2

1

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 %>
...
Sign up to request clarification or add additional context in comments.

Comments

0

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 )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.