Rails 5 - turbolinks 5,some JS not loaded on page render

With turbolinks the javascript is only loaded once. On the hard refresh chosen works because the entire page is re-rendered. Once you click a link, turbolinks hijacks the request and turns it into an ajax one (instead of a full page refresh). Once the request comes in, turbolinks only replaces the body of the page, leaving the JS in the same state it was.

To fix this you will need to wrap your chosen initializer in the turbolinks:load event like so

$(document).on('turbolinks:load', function() {
  $('#screen-selection').chosen({
    width: '190px'
  })
})

For more information, see https://github.com/turbolinks/turbolinks#installing-javascript-behavior


Here is my solution with Turbolinks 5 and jQuery:

  1. install gem 'jquery-turbolinks'

  2. add this .coffee file to your app: https://github.com/turbolinks/turbolinks/blob/master/src/turbolinks/compatibility.coffee

  3. name it turbolinks-compatibility.coffee

  4. at application.js

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

//=require turbolinks
//=require turbolinks-compatibility


I got a serious headache to find a way to make all my javascript work. First i try the solution with the gem jquery.turbolinks by following this video: How to upgrade to turbolinks 5 but i got lightbox for showing the images in the same page not working properly. So before just disable Turbolinks once and for all, i take more time on the github page and i try this:

<div data-turbolinks="false">
  <a href="/">Disabled</a>
</div>

You need to put that on each link where the javascript need a page reload to work.

Maybe its not the best solution, but that make my headache less painful.