In my Rails app, I have a number of JS files I would like to be always available, and have placed them in app/assets/javascripts/globals
, compiling them from application.js
via //= require_tree ./globals
.
However, I have some JS files that are view specific, and would prefer if they were only implemented for certain views or controllers. They're currently compiled in config/initializers/assets.rb
via Rails.application.config.assets.precompile += %w( foo.js bar.js )
, and accessed via <%= javascript_include_tag "foo/bar", "data-turbolinks-track" => true %>
in the respective views.
I've wrapped the essential functions in foo.js
& bar.js
in conditionals such as if $("#foo").length > 1 ...
, which prevents their functionality if the required divs aren't present.
As a result, the JS files aren't "active" until after the view is visited. However, after being visited, the JS code is "active" even after visiting another view. Is there a control mechanism that will ensure that the JS code is being read only for the correlating views?