2slkkg
Last Updated: February 25, 2016
·
620
· hendrikpetertje

Using Document ready with turbolinks

Normaly you would type these coffescript lines when using code that should run after the document finished loading.

$(document).ready ->
  your code here

But in new versions of rails the header of the application's layout view has this script linked: data-turbolinks-track. When you click links with this page value set to true, the currently loaded page get's filled with new content instead of a new page loading. this saves time in requesting pages and their default assets. but re-appending content does not trigger '$(document).ready ->'. It will however restart every javascript and read all the lines and functions again. That's why we are going to change some values at the top and add some to the bottom.

ready = ->
  Your code here

$(document).ready(ready)
$(document).on('page:load', ready)

ready in line 2 is a variable that stores a function. When called it will run the indented code.

Below the javascript version

var ready;
ready = function() {

  Your code here

};

$(document).ready(ready);
$(document).on('page:load', ready);

1 Response
Add your response

14629

I have encoutered this problem too. Nice tip!

over 1 year ago ·