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 separate files and compile them with the assets pipeline. However, I just learned that jQuery's "ready" event doesn't fire on subsequent clicks when turbo-linking is turned on. The first time you load a page it works. But when you click a link, anything inside the ready( function($) {
won't get executed (because the page doesn't actually load again). Good explanation: here.
So my question is: What is the right way to ensure that jQuery events work properly while turbo-links are on? Do you wrap the scripts in a Rails-specific listener? Or maybe rails has some magic that makes it unnecessary? The docs are a bit vague on how this should work, especially with respect to loading multiple files via the manifest(s) like application.js.
Recently I found the most clean and easy to understand way of dealing with it:
OR
EDIT
If you have delegated events bound to the
document
, make sure you attach them outside of theready
function, otherwise they will get rebound on everypage:load
event (causing the same functions to be run multiple times). For example, if you have any calls like this:Take them out of the
ready
function, like this:Delegated events bound to the
document
do not need to be bound on theready
event.First, install
jquery-turbolinks
gem. And then, don't forget to move your included Javascript files from end of body of yourapplication.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.
You have to use:
from turbolinks doc.
I figured I'd leave this here for those upgrading to Turbolinks 5: the easiest way to fix your code is to go from:
to:
Reference: https://github.com/turbolinks/turbolinks/issues/9#issuecomment-184717346
As per the new rails guides, the correct way is to do the following:
or, in coffeescript:
Do not listen to the event
$(document).ready
and only one event will be fired. No surprises, no need to use the jquery.turbolinks gem.This works with rails 4.2 and above, not only rails 5.
maybe you can use like this to use "ready", it just like close your turbolink.