Search code examples
javascriptruby-on-railsruby-on-rails-4turbolinks

Rails 4: jquery-turbolinks causing "Uncaught TypeError: Cannot read property 'length' of undefined"


My Javascript is only loading after refreshing the page in Rails. After looking into it, the recommend solution seems to be to use turbolinks. However, when I include the jquery-turbolinks gem, JQuery itself seems to crash presumably due to some dependency error.

Uncaught TypeError: Cannot read property 'length' of undefined

Here's what my application.js file is looking like

//= require turbolinks
//= require angular/angular.min
//= require angular/angular-route.min
//= require jquery
//= require jquery_ujs
//= require jquery-ui.min
//= require jquery.turbolinks
//= require chosen-jquery
//= require bootstrap
//= require conversations
//= require analytics
//= require common
//= require jquery.infinite-pages
//= require jquery.contenthover
//= require overlay
//= require tag-it.min
//= require_tree .
//= require_tree ../../../vendor/assets/javascripts/.

So to sum it up, if I don't use jquery-turbolinks, my JS won't load until after a page refresh. If I do use it, jQuery crashes. If i try to put it before require jquery, it can't find the JQuery file and said $ is not a function.


Solution

  • Order the jQuery.turbolinks just after jQuery

    //= require turbolinks
    //= require angular/angular.min
    //= require angular/angular-route.min
    //= require jquery
    //= require jquery.turbolinks
    //= require jquery_ujs
    //= require jquery-ui.min
    

    That's the way the jQuery.turbolinks will work correctly