Lazy Loading Video and Media Elements
You'll learn how to defer loading heavy video and media content until it's needed, slashing initial page load times.
Videos are often the heaviest assets on a page—sometimes multiple megabytes. Loading them all upfront wastes bandwidth and delays your page's interactivity, especially on mobile networks. Just like with images, you can lazy load videos so they only download when users are about to see them.
Native Lazy Loading for Video Posters
The loading="lazy" attribute works on video poster images:
<video poster="thumbnail.jpg" loading="lazy" controls>
<source src="large-video.mp4" type="video/mp4">
</video>
The poster image won't load until the video scrolls near the viewport.
Removing preload Attribute
By default, browsers may start downloading video metadata or even partial content. Prevent this with preload="none":
<video preload="none" poster="thumbnail.jpg" controls>
<source src="video.mp4" type="video/mp4">
</video>
This tells the browser: "Don't download anything until the user clicks play."
Using Intersection Observer for Full Control
For videos that should load as they approach the viewport (even before user interaction), use the Intersection Observer you already know:
const videos = document.querySelectorAll('video[data-src]');
const videoObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const video = entry.target;
video.src = video.dataset.src;
video.load();
videoObserver.unobserve(video);
}
});
});
videos.forEach(video => videoObserver.observe(video));
Think of it like a warehouse: instead of delivering all packages at once, you only ship items when the customer enters your neighborhood.
Key Takeaway: Use preload="none" and Intersection Observer to defer video loading until needed, dramatically reducing initial page weight and improving perceived performance.