javascript - 当放置在 Rails 的 HEAD 中时,jQuery 就绪事件不会在每个页面加载时触发

标签 javascript jquery ruby-on-rails document-ready

在 Rails 中使用 jQuery 就绪事件时,我注意到一些奇怪的事情。如果在<head>中添加处理程序部分,直接在脚本标签内或在使用 <%= javascript_include_tag ... 包含的 Assets 管道文件中,它只会在第一个页面请求上执行,而不会在后续请求上执行。也就是说,加载/刷新页面的显式浏览器操作将执行它,但通过单击链接触发的新页面 View 不会执行。

另一方面,如果它包含在<body>中,它每次在每次页面浏览时都会触发 - 就像您所期望的那样。

<head>
<script>
jQuery(document).ready(function(){
    console.log('READY in head'); // Fires on first page load only
});
</script>
</head>

<body>
<script>
jQuery(document).ready(function(){
    console.log('READY in body'); // Fires every time
});
</script>
</body>

真的很困惑。我在所有 Rails 应用程序中都看到了它,但不明白 Rails 如何实现这一点,因为 jQuery 是一种客户端技术?

最佳答案

来自RailsApps Project :

The Rails asset pipeline will become even more important in Rails 4.0 with the new Turbolinks feature. Turbolinks improves performance by keeping the current page instance alive and replacing only the page BODY (plus the title in the HEAD). As long as the HEAD element is identical between pages, the Turbolinks mechanism can deliver its “turbo” speed boost. This adds to the importance of avoiding any extra script tags on specific pages.

关于javascript - 当放置在 Rails 的 HEAD 中时,jQuery 就绪事件不会在每个页面加载时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17746566/

相关文章:

javascript - 使用 JavaScript/jQuery 搜索 JSON 数组

javascript - 从函数 jquery 内的函数获取值

ruby-on-rails - Rails 服务器 : more verbosity

javascript - 根据它悬停的页面部分的背景更改固定导航栏的类

jquery - 如何手动加载jqgrid中的数据?

ruby-on-rails - rails active_storage :install IS NOT WORKING

ruby-on-rails - 无法在 postgresql 中创建数据库

javascript - 奇怪的 ng-model 行为(ng-model 映射到数组元素)

javascript - 根据下面的 div 颜色更改粘性导航颜色

javascript - JS : how do I concatenate a variable into a API call with the dot syntax?