Turbolinks加载事件不适用于页面刷新 [英] Turbolinks load event not working on with page refresh
问题描述
像这样的Javascript代码
Javascript code like this
document.addEventListener("turbolinks:load", function() {
$("p#hide_if_js").hide();
});
当我在页面之间单击或使用浏览器后退按钮时,
可以很好地与Turbolink配合使用.但是,当我刷新页面时,未加载javascript代码.如果我刷新几次,则什么也没有发生,但是,如果我单击指向其他背面的链接并单击返回该页面,则现在已加载javascript代码.
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.
看来,turbolinks:load在大多数事件上都起作用,但是页面重新加载却没有.该文档说,它在初始页面加载时触发一次,并在每次访问Turbolinks之后触发".怎么了?
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?
我正在使用jquery.turbolinks gem和关联的兼容性代码.
I am using the jquery.turbolinks gem and the associated compatibility code.
推荐答案
在 uzaif的注释的帮助下,以下工作有效
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)
$('body').attr('data-loaded')
行可防止代码两次加载.
The $('body').attr('data-loaded')
lines are to prevent the code loading twice.
按照turbolinks说明的建议,此方法使用事件委托.目前尚不清楚为什么仍需要使用 $(document).ready(ready)
,因为 turbolink:load
旨在解决这一问题.
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.
这篇关于Turbolinks加载事件不适用于页面刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!