1

I have page1, page2 and page3 in my Rails application.

For page2 I have a special javascript file with some jQuery .click events.

I include the file to my application.js //= require specialfile The specialfile is in my app/assets/javascripts/specialfile.js path.

I figured out that if I will go from page1 or page3 to the page2, the special js file doesn't work unless I will refresh the page. It works only if I will go directly to the page2 without any previous move.

I tried not to require the specialfile.js in my application.js pipeline and include it directly to my page2 by: <%= javascript_include_tag "specialfile" %>. It didn't work. I also tried to add there the full path like assets/javascript/specialfile.js ... app/assets/javascript/specialfile but no luck.

How can I do it?

I found something like: <%= javascript_include_tag params[:controller] if AppName::Application.assets.find_asset("#{params[:controller]}.js") %> but I don't understand well. How I can point to the specialfile?

3
  • In Page1 & Page2, when view page source, do you see specialfile.js file? Commented Mar 22, 2016 at 0:19
  • What you mean? If I have it in my application.js, it works everywhere, but there is an issue with this: forum.jquery.com/topic/script-not-running-unless-i-refresh-page ... If I try to point on it with the javascript_include_tag "specialfile.js" it will show 404 not found in the console. Commented Mar 22, 2016 at 0:27
  • If it's loaded but didn't work, please consider turbolinks. Commented Mar 22, 2016 at 0:34

1 Answer 1

2

By default Rails includes the turbolinks gem, which loads just the body of the page when you click on a link without doing a full load of the whole page. Because it's no longer doing a full reload of the page, the "ready" event on document is not triggered.

You should read the turbolinks README, especially this bit on Events for more information, but generally the quick way around this is instead of your code being in a $(... or $(document).ready block you should put it in:

$(document).on("ready page:load", ...
Sign up to request clarification or add additional context in comments.

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.