0

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?

  • I recently answered this on [Rails - how to include Javascript files only on certain pages](http://stackoverflow.com/questions/37360023/rails-how-to-include-javascript-files-only-on-certain-pages) – Michael Gaskill May 28 '16 at 21:20
  • maybe [THIS](http://brandonhilkert.com/blog/page-specific-javascript-in-rails/) will help you – Oleh Sobchuk May 28 '16 at 22:41

1 Answers1

0

http://brandonhilkert.com/blog/page-specific-javascript-in-rails/ http://brandonhilkert.com/blog/organizing-javascript-in-rails-application-with-turbolinks/

This is how I've implemented view specific, though it's a real pain.

Essentially, you'll be building a script namespace that contains scripts that are triggered always or only on specific controllers or even actions.

Rails also provides a way of doing controller specific. http://guides.rubyonrails.org/asset_pipeline.html#controller-specific-assets

I'd honestly try this instead as it's pretty simple. I'm also supposing, looking at the implementation that you could easily do action based as well.

As for you're "active" code issue.

1) Ensure you are using on document ready (and/or page:load for turbolinks depending on version).

2) Ensure that your scripts work to begin with.

3) Ensure that they're working for both page refresh and turbolink visit.

Depending on how and when it breaks, it could mean different problems.

MarsAtomic
  • 10,436
  • 5
  • 35
  • 56
fbelanger
  • 3,522
  • 1
  • 17
  • 32