Load videos only when they're about to be viewed
These videos won't load until they're 200px from entering the viewport. Watch the status badges change from "Pending" to "Loaded".
// Create observer with 200px root margin (preload before visible)
const videoObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const video = entry.target;
// Set the src from data attribute
video.src = video.dataset.src;
video.load();
// Stop observing this video
videoObserver.unobserve(video);
}
});
}, {
rootMargin: '200px 0px' // Load 200px before entering viewport
});
// Observe all videos with data-src
document.querySelectorAll('video[data-src]').forEach(video => {
videoObserver.observe(video);
});