我正在学习 Rails,并且正在为特定于页面的 javascript 的最佳实践而苦苦挣扎。即使使用这种简单的方法,turbolinks(我相信)也会导致 javascript 在我访问一个页面然后返回时执行两次。
为了简化场景,我创建了一个包含两个 Controller 操作的新项目,并启动了一个服务器。
rails new jstest
cd jstest
rails g controller home index index2
rails server
现在我将 View 更新为以下内容:
index.html.erb:
<%= link_to "Index2", home_index2_path %>
<script>
console.log("hi from index!");
</script>
index2.html.erb:
<%= link_to "Index", home_index_path %>
<script>
console.log("hi from index2!");
</script>
通过导航到/home/index,通过指向 index2 的链接,然后返回到我希望看到的索引的链接:
hi from index!
hi from index2!
hi from index!
但是,我两次收到第三条消息:
hi from index!
hi from index2!
hi from index!
hi from index!
为什么我的 javascript 在第二次访问索引时执行了两次,是否有更好的方法来设置页面特定的 javascript 以避免执行两次?
感谢您的帮助。
最佳答案
这是由 turbolinks 在重新访问页面时显示预览引起的。我的理解是 turbolinks 会短暂显示预览,以改善感知加载时间,然后替换它。在我的示例中,Javascript 在显示预览时和在替换时再次执行。
在我的场景中,执行两次 javascript 不会造成任何不良副作用,但如果是的话,可以通过使用以下命令禁用预览来停止,根据他们的 documentation :
<head>
...
<meta name="turbolinks-cache-control" content="no-preview">
</head>
关于javascript - rails 5 : Why is javascript executing twice?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40054060/