[英]javascript doesn't load unless I refresh
I've got some jquery in $(document).ready()
, but this jquery code doesn't run on my page unless I refresh the page. 我在
$(document).ready()
有一些jquery,但是除非刷新页面,否则此jquery代码不会在我的页面上运行。 Then it works on every subsequent refresh. 然后,它将在以后的每次刷新中起作用。 Why is this the case?
为什么会这样呢?
I'm just putting in javascript and html tags but I'm working in a rails app, not sure if that complicates things. 我只是放入javascript和html标签,但是我在Rails应用程序中工作,不确定是否会使事情复杂化。
Depending on your turbolinks version, you have to use the right syntax to override document load event. 根据您的turbolinks版本,您必须使用正确的语法来覆盖文档加载事件。 For turbolinks 5:
对于Turbolinks 5:
instead of 代替
$(document). ready(function () {
....
})
Use 采用
var documentready = function(){
}
$(document). on('turbolinks:load', documentready);
This will gracefully fall back to document ready event when refreshing. 刷新时,它将优雅地退回到文档就绪事件。
Why is this necessary? 为什么这是必要的?
Turbolinks binds location changes (like clicking links) and uses Ajax to load the partial. Turbolinks绑定位置更改(例如单击链接),并使用Ajax加载部分内容。 The document IS NOT LOADED.
未加载文档。 Also, it manipulates browser's history to record the visit.
此外,它还操纵浏览器的历史记录来记录访问。
So, the assets are not loaded on each visit. 因此,不会在每次访问时加载资产。 Fast.
快速。 That's why document ready won't bind on all events, unless all listeners are targeted under body or document (eg
$("body").on("click","selector",function()...
instead of $("selector").on('click', function()...
这就是为什么文档就绪不会绑定所有事件的原因,除非所有侦听器都针对正文或文档(例如
$("body").on("click","selector",function()...
而不是$("selector").on('click', function()...
This problem occurs because some of the key events in older version of turbolinks is not compatible with the new turbolinks 5. 发生此问题的原因是旧版本的turbolinks中的某些关键事件与新的turbolinks 5不兼容。
I suggested download the gem jquery-turbolinks
make sure to require to application.js
我建议下载
gem jquery-turbolinks
确保确保对application.js
要求
//= require jquery
//= require jquery.turbolinks
......
and the compatibility script .You can find the script here just create a compatibility.coffee
under assets/javascripts
和兼容性脚本。您可以在此处找到该脚本,只需在
assets/javascripts
下创建一个compatibility.coffee
This will let you use the old syntax. 这将使您使用旧语法。
$(document).ready...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.