在 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 是一种客户端技术?
最佳答案
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/