Skip to content Skip to sidebar Skip to footer

Rails 4 Turbo-link Prevents Jquery Scripts From Working

I'm building a Rails 4 app and I have a few scattered js files that I'm trying to include 'the rails way'. I moved jquery plugins into the /vendor/assets/javascripts and I updated

Solution 1:

$(document).ready(function(){ doesn't really work with Turbolinks. Turbolinks:

... makes following links in your web application faster. Instead of letting the browser recompile the JavaScript and CSS between each page change, it keeps the current page instance alive and replaces only the body and the title in the head.

So the page is only loaded once and then pieces are replaced as needed. Since the page is only loaded once, your $(document).ready() callbacks are only triggered when the site is initially visited, you won't get more document-ready events when switching pages because Turbolinks doesn't actually switch pages. From the fine manual:

With Turbolinks pages will change without a full reload, so you can't rely on DOMContentLoaded or jQuery.ready() to trigger your code. Instead Turbolinks fires events on document to provide hooks into the lifecycle of the page.

You probably want to listen for one of the Turbolinks events instead:

  • page:change the page has been parsed and changed to the new version and on DOMContentLoaded
  • [...]
  • page:load is fired at the end of the loading process.

page:change is usually what you're looking for as it is triggered when loading a fresh page and restoring a page from the Turbolinks page cache.

You might want to turn off Turbolinks until you've had time to review all of your JavaScript and you've done a full QA sweep. You should also test your site's speed to see if it is worth using at all.

Another option would be to use jquery.turbolinks to patch up things for you. I haven't used this but other people are using it to good effect.

Solution 2:

A solution to this is already available at this railscast

Here is one example (the one i like to use).

ready = ->
  # ..... your js$(document).ready(ready)
$(document).on('page:load', ready)

There is also a gem that solves this issue in a way that lets you keep doing it the old way. It works really well :)

Solution 3:

I realize this Answer is REAAAAAAALLLLLLLYYYYY Late... but I figured I'd add it.

I just had this issue last week.. While trying to get Foundation to work..

First I added:

gem 'jquery-turbolinks'

Then Placed it in application.js like so:

//= require jquery.turbolinks//= require jquery_ujs//= require turbolinks//= require_tree .

and then I added this right below it:

$(document).on('turbolinks:load', function() {

});

and everything worked for me. Hope this helps!

Post a Comment for "Rails 4 Turbo-link Prevents Jquery Scripts From Working"