Rails 4: how to use $(document).ready() with turbo-links

前端 未结 19 1560
忘了有多久
忘了有多久 2020-11-21 06:52

I ran into an issue in my Rails 4 app while trying to organize JS files \"the rails way\". They were previously scattered across different views. I organized them into separ

相关标签:
19条回答
  • 2020-11-21 07:30

    None of the above works for me, I solved this by not using jQuery's $(document).ready, but use addEventListener instead.

    document.addEventListener("turbolinks:load", function() {
      // do something
    });
    
    0 讨论(0)
  • 2020-11-21 07:30

    You have to use:

    document.addEventListener("turbolinks:load", function() {
      // your code here
    })
    

    from turbolinks doc.

    0 讨论(0)
  • 2020-11-21 07:30

    First, install jquery-turbolinks gem. And then, don't forget to move your included Javascript files from end of body of your application.html.erb to its <head>.

    As described here, if you have put the application javascript link in the footer for speed optimization reasons, you will need to move it into the tag so that it loads before the content in the tag. This solution worked for me.

    0 讨论(0)
  • 2020-11-21 07:33

    I just learned of another option for solving this problem. If you load the jquery-turbolinks gem it will bind the Rails Turbolinks events to the document.ready events so you can write your jQuery in the usual way. You just add jquery.turbolinks right after jquery in the js manifest file (by default: application.js).

    0 讨论(0)
  • 2020-11-21 07:33

    I figured I'd leave this here for those upgrading to Turbolinks 5: the easiest way to fix your code is to go from:

    var ready;
    ready = function() {
      // Your JS here
    }
    $(document).ready(ready);
    $(document).on('page:load', ready)
    

    to:

    var ready;
    ready = function() {
      // Your JS here
    }
    $(document).on('turbolinks:load', ready);
    

    Reference: https://github.com/turbolinks/turbolinks/issues/9#issuecomment-184717346

    0 讨论(0)
  • 2020-11-21 07:34
    $(document).on 'ready turbolinks:load', ->
      console.log '(document).turbolinks:load'
    
    0 讨论(0)
提交回复
热议问题