Boost Your Page Speed: Implementing Lazy Loading for Videos
Topics covered in this article:
Slow-loading websites frustrate users and hurt your SEO rankings. While optimizing video file sizes with tools like TinyVid.io is crucial (see our guide on reducing video size), when those videos load also matters immensely. If you have videos below the fold (not immediately visible), loading them instantly wastes bandwidth and delays rendering critical content.
The solution? Lazy loading.
What is Lazy Loading for Videos?
Lazy loading is a technique that defers the loading of non-critical resources (like images or videos) until they are actually needed – typically, just before they scroll into the user’s viewport. Instead of loading all videos upfront, you load only what’s necessary for the initial view, significantly speeding up the initial page load.
Why Lazy Load Videos?
- Faster Initial Page Load: Reduces the number of initial requests and the amount of data downloaded, leading to quicker rendering and a better user experience.
- Improved Core Web Vitals:
- Largest Contentful Paint (LCP): By not competing for bandwidth, critical above-the-fold content can load faster, improving LCP.
- First Input Delay (FID) / Interaction to Next Paint (INP): Reduces main thread blocking during the initial load, making the page interactive sooner.
- Reduced Bandwidth Consumption: Saves data for both the user and the server, especially important for users on limited data plans.
- Better SEO: Page speed is a confirmed ranking factor. Faster sites generally rank better.
How to Implement Lazy Loading for Videos
There are several ways to lazy load videos:
1. Native HTML loading="lazy"
(Simplest)
Modern browsers support native lazy loading for <iframe>
elements, which is commonly used for embedding videos (like YouTube or Vimeo).
<iframe
src="https://www.youtube.com/embed/your_video_id"
width="560"
height="315"
title="Your Video Title"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
loading="lazy"
>
<!-- Add this attribute -->
</iframe>
Pros: Extremely simple, no JavaScript required.
Cons: Only works for <iframe>
s, not directly for HTML <video>
tags. Browser support is good but not universal (older browsers ignore it).
2. JavaScript using the Intersection Observer API (Most Flexible)
This is a powerful, efficient way to detect when an element enters the viewport. It’s ideal for lazy loading HTML <video>
elements or creating custom solutions.
Concept:
- Initially, don’t put the video source in the
src
attribute. Usedata-src
instead. - Use the
poster
attribute to show a placeholder image. - Use Intersection Observer to watch the video element.
- When the video element is about to enter the viewport, swap
data-src
tosrc
to trigger the video load.
Example Implementation:
<!-- Add a class for JS targeting -->
<video
class="lazy-video"
width="640"
height="360"
controls
preload="none"
poster="path/to/your/placeholder-thumbnail.jpg"
>
<source data-src="path/to/your/video.mp4" type="video/mp4" />
<!-- Add other sources if needed -->
Your browser does not support the video tag.
</video>
<video class="lazy-video" ...>...</video>
<!-- More videos -->
document.addEventListener("DOMContentLoaded", function () {
const lazyVideos = [].slice.call(
document.querySelectorAll("video.lazy-video"),
);
if ("IntersectionObserver" in window) {
let lazyVideoObserver = new IntersectionObserver(
function (entries, observer) {
entries.forEach(function (videoEntry) {
if (videoEntry.isIntersecting) {
const video = videoEntry.target;
// Find source elements within the video tag
for (const source in video.children) {
const videoSource = video.children[source];
if (
typeof videoSource.tagName === "string" &&
videoSource.tagName === "SOURCE"
) {
// Swap data-src to src
if (videoSource.dataset.src) {
videoSource.src = videoSource.dataset.src;
}
}
}
// Load the video
video.load();
// Optional: Add class to prevent re-observing
video.classList.remove("lazy-video");
// Stop observing this video
lazyVideoObserver.unobserve(video);
}
});
},
{
// Optional: Load video slightly before it enters viewport
rootMargin: "0px 0px 200px 0px", // Load 200px before viewport bottom
},
);
lazyVideos.forEach(function (lazyVideo) {
lazyVideoObserver.observe(lazyVideo);
});
} else {
// Fallback for browsers without IntersectionObserver
// You could load all videos immediately, or use an older method.
lazyVideos.forEach(function (video) {
for (const source in video.children) {
const videoSource = video.children[source];
if (
typeof videoSource.tagName === "string" &&
videoSource.tagName === "SOURCE"
) {
if (videoSource.dataset.src) {
videoSource.src = videoSource.dataset.src;
}
}
}
video.load();
});
}
});
Pros: Works for HTML <video>
, highly efficient, customizable (e.g., load threshold).
Cons: Requires JavaScript, slightly more complex setup.
3. Third-Party Libraries
Libraries like Lozad.js or vanilla-lazyload abstract the Intersection Observer logic, potentially simplifying implementation.
Pros: Can be easier if you’re less comfortable with vanilla JS. Cons: Adds another dependency to your project.
Combining Lazy Loading with Video Optimization
Lazy loading solves when the video loads, but the video file itself still needs to be optimized for size and format. A lazy-loaded but massive video file will still cause jank when it finally loads and starts playing.
This is where TinyVid.io comes in. By first optimizing your videos for the web (compressing, choosing the right codec/format), and then implementing lazy loading, you achieve the maximum performance benefit:
- Optimize: Use TinyVid to drastically reduce video file size without losing quality.
- Lazy Load: Implement one of the methods above to defer loading.
This combination ensures a fast initial page load and a smooth video loading/playback experience when the user scrolls down.
Conclusion
Lazy loading videos is no longer optional for performance-conscious websites. Whether using the simple native loading="lazy"
attribute for iframes or the more flexible Intersection Observer API for HTML <video>
tags, deferring video loading is a critical technique. Combine it with robust video optimization using tools like TinyVid.io to deliver a lightning-fast experience that users and search engines will love.