09. Lazy Loading Video

Load videos only when they're about to be viewed

Scroll down to see videos load on demand
↓ Keep scrolling to reach the videos ↓

Lazy Loaded Videos

These videos won't load until they're 200px from entering the viewport. Watch the status badges change from "Pending" to "Loaded".

Pending

Nature Video 1

Loads when scrolled into view

Pending

Nature Video 2

Loads when scrolled into view

Pending

Nature Video 3

Loads when scrolled into view

Implementation Code

// 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);
});