Turbolinks load event not working on with page refresh

三世轮回 提交于 2019-11-28 03:34:57

问题


Javascript code like this

document.addEventListener("turbolinks:load", function() {
  $("p#hide_if_js").hide();
});

is working fine with turbolinks when I click between pages or use the browser back button. However, when I refresh the page, the javascript code is not loaded. If I refresh a few times, nothing happens, but if I click a link to a different back and click back to the page, the javascript code is now loaded.

It looks like the turbolinks:load is working on most events, but not the page reload. The documentation says that it 'fires once on the initial page load and again after every Turbolinks visit'. What is going wrong?

I am using the jquery.turbolinks gem and the associated compatibility code.


回答1:


With help from uzaif's comment, the following worked

  ready = ->
    if $('body').attr('data-loaded') == 'T'
      return
    # code goes here
    $('body').attr('data-loaded','T')
  $(document).ready(ready)
  $(document).on('turbolinks:load', ready)

The $('body').attr('data-loaded') lines are to prevent the code loading twice.

This approach is using event delegation, as recommended by the turbolinks instructions. It is not clear why it is still necessary to use the $(document).ready(ready) as the turbolink:load is meant to cover this.




回答2:


You can use in this manner

document.addEventListener('load turbolinks:load',function() {
//Your code
});

equivalent coffee code

document.addEventListener 'load turbolinks:load', ->
  #Your code
  return



回答3:


$(document).on('turbolinks:load', function() {
  // enter code here
});


来源:https://stackoverflow.com/questions/41421496/turbolinks-load-event-not-working-on-with-page-refresh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!