这是由于 Turbolinks 缓存了主页 DOM 的副本。即使视频不可见,它仍然存在于缓存中,因此会播放。 (但是,我不确定为什么它没有被静音——这可能是一个浏览器错误:/)
我认为 Turbolinks 可以默认处理这个问题,但与此同时,这里有几个选项:
解决方案 1:在首页禁用缓存
为防止 Turbolinks 缓存主页的副本,您可以禁用该页面的缓存。例如,您可以在布局的<head> 中包含以下内容:
<% if @turbolinks_cache_control %>
<meta name="turbolinks-cache-control" content="<%= @turbolinks_cache_control %>">
<% end %>
然后在您的主页视图中:
<% @turbolinks_cache_control = 'no-cache' %>
缺点是当访问者重新访问主页时,您会错过性能优势。
解决方案 2:跟踪 autoplay 元素
或者,您可以跟踪autoplay 元素,在缓存页面之前删除autoplay 属性,然后在呈现之前重新添加它。与Persisting Elements Across Page Loads 类似,此解决方案要求autoplay 元素具有唯一ID。
在您的应用程序 JavaScript 中包含以下内容:
;(function () {
var each = Array.prototype.forEach
var autoplayIds = []
document.addEventListener('turbolinks:before-cache', function () {
var autoplayElements = document.querySelectorAll('[autoplay]')
each.call(autoplayElements, function (element) {
if (!element.id) throw 'autoplay elements need an ID attribute'
autoplayIds.push(element.id)
element.removeAttribute('autoplay')
})
})
document.addEventListener('turbolinks:before-render', function (event) {
autoplayIds = autoplayIds.reduce(function (ids, id) {
var autoplay = event.data.newBody.querySelector('#' + id)
if (autoplay) autoplay.setAttribute('autoplay', true)
else ids.push(id)
return ids
}, [])
})
})()
此脚本在页面缓存之前获取所有autoplay 元素,将每个ID 存储在autoplayIds 中,然后删除autoplay 属性。当一个页面即将被渲染时,它会遍历存储的 ID,并检查新正文是否包含具有匹配 ID 的元素。如果是,则重新添加autoplay 属性,否则将ID 推送到新的autoplayIds 数组。这可确保autoplayIds 仅包含尚未重新渲染的 ID。