I ran into an issue in my Rails 4 app while trying to organize JS files \"the rails way\". They were previously scattered across different views. I organized them into separ
None of the above works for me, I solved this by not using jQuery's $(document).ready, but use addEventListener instead.
document.addEventListener("turbolinks:load", function() {
// do something
});
You have to use:
document.addEventListener("turbolinks:load", function() {
// your code here
})
from turbolinks doc.
First, install jquery-turbolinks
gem. And then, don't forget to move your included Javascript files from end of body of your application.html.erb
to its <head>
.
As described here, if you have put the application javascript link in the footer for speed optimization reasons, you will need to move it into the tag so that it loads before the content in the tag. This solution worked for me.
I just learned of another option for solving this problem. If you load the jquery-turbolinks gem it will bind the Rails Turbolinks events to the document.ready
events so you can write your jQuery in the usual way. You just add jquery.turbolinks
right after jquery
in the js manifest file (by default: application.js
).
I figured I'd leave this here for those upgrading to Turbolinks 5: the easiest way to fix your code is to go from:
var ready;
ready = function() {
// Your JS here
}
$(document).ready(ready);
$(document).on('page:load', ready)
to:
var ready;
ready = function() {
// Your JS here
}
$(document).on('turbolinks:load', ready);
Reference: https://github.com/turbolinks/turbolinks/issues/9#issuecomment-184717346
$(document).on 'ready turbolinks:load', ->
console.log '(document).turbolinks:load'