Rails: use $(document).ready() with Turbolinks

by Giang, last updated 26 Feb 2018

If you are not familiar with Turbolinks, you could get weird bug related to Javascript interactions that are fired in $(document).ready() event when navigating between pages. This post introduces possible solutions for this issue.

For Rails 5 or Rails apps that use Turbolinks 5

// no need for $(document).ready()
$(document).on('turbolinks:load', function() {
  // code goes here
});

For Rails 4 apps that uses old Turbolinks

var ready;
ready = function() {
  // code goes here
}
$(document).ready(ready);
$(document).on('page:load', ready);

Or

$(document).on('ready page:load', function () {
  // code goes here
});

Or

$(document).on('page:change', function () {
  // code goes here
});