1

SO I've just started using coffeescript in a Rails 4 app and hitting a strange issue whereby the resultant js isn't always running

The only coffeescript I've written is a simple log statement:

$ ->
    console.log "show this"

This seems to pop up sporadically for first page loads. If it doesn't load and I refresh the page then it loads the following time.

Am I missing something here?

Gerard
  • 4,688
  • 5
  • 48
  • 76

2 Answers2

0

Yep, it's caused by Turbolinks.

$ ->
  console.log "show this"

means

$(function(){
  console.log("show this")
})

which means

$(document).ready(function(){
  console.log("show this")
})

Turbolinks intercepts the requests so that the ready event isn't triggered.


To solve this, you can either disable Turbolinks or use jquery-turbolinks.

Ju Liu
  • 3,859
  • 11
  • 18
0

Take a look at this question: Rails 4 turbo-link prevents jQuery scripts from working

You want to add a page:change event listener since Turbolinks suppresses $(document).ready

So something like this should fix the issue:

$(document).on('page:change', function() { ... })
Community
  • 1
  • 1
pthamm
  • 1,811
  • 1
  • 12
  • 15