I'm having some trouble loading my javascript when I use a link_to helper in rails. When I either manually enter the url with 'localhost:3000/products/new' or reload the page, the javascript loads, but when I go through a link as written below, the jQuery $(document).ready
will not load on the new page.
Link_to, javascript does not load when I click this link:
<%= link_to "New Product", new_product_path %>
products.js file
$(document).ready(function() {
alert("test");
});
Any help would be much appreciated. Thanks in advance!
Make sure you don't have any inline
<script>
tags. (Inline script tags are bad with turbolinks).FWIW, from the Turbolinks docs, the more appropriate event to capture instead of the
$(document).ready
ispage:change
.page:load
has a caveat that it doesn't fire on cache reloads...And since Turbolinks is just switching the view,
page:change
is more appropriate.If you are on rails 5 instead of
'page:change'
you should use'turbolinks:load'
like this:Source: https://stackoverflow.com/a/36110790
I got the same probleme but jquery.turbolinks doesn't helped. I noticed that I have to override the GET method.
There is my sample :
You can also wrap your link with a div that specifies data-no-turbolink.
Example:
Source: https://github.com/rails/turbolinks
Are you using Rails 4? (Find out by doing
rails -v
in your console)This issue is probably due to the newly added Turbolinks gem. It makes your application behave like a single page JavaScript application. It has a few benefits (it's faster), but it unfortunately breaks some existing events like
$(document).ready()
because the page is never reloaded. That would explain why the JavaScript works when you directly load the URL, but not when you navigate to it through alink_to
.Here's a RailsCast about Turbolinks.
There are a couple solutions. You can use jquery.turbolinks as a drop-in fix, or you can switch your
$(document).ready()
statement to instead use the Turbolinks'page:change'
event:Alternatively, you could do something like this for compatibility with regular page loads as well as Turbolinks:
If you are using Ruby on Rails >5 (you can check by running
rails -v
in the console) use'turbolinks:load'
instead of'page:change'