Pause Autoplaying Videos When Off Screen
Pauses background and autoplaying videos when they scroll out of view or the browser tab is hidden, and resumes them when they come back, saving battery and data.
Opens WPIDE on
Code
(function () {
var videos = Array.prototype.filter.call(document.querySelectorAll('video[autoplay]'), function (v) { return v.muted; });
if (!videos.length || !('IntersectionObserver' in window)) { return; }
var visible = new Set();
function resume(v) { var p = v.play(); if (p && p.catch) { p.catch(function () {}); } }
var io = new IntersectionObserver(function (entries) {
entries.forEach(function (entry) {
if (entry.isIntersecting) { visible.add(entry.target); if (!document.hidden) { resume(entry.target); } }
else { visible.delete(entry.target); entry.target.pause(); }
});
}, { threshold: 0.1 });
videos.forEach(function (v) { io.observe(v); });
document.addEventListener('visibilitychange', function () {
videos.forEach(function (v) { if (document.hidden) { v.pause(); } else if (visible.has(v)) { resume(v); } });
});
})();
Notes
Only affects videos that autoplay muted, such as Cover block background videos.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.