Boost Your Page Speed: Implementing Lazy Loading for Videos

5 min read

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?

  1. 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.
  2. 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.
  3. Reduced Bandwidth Consumption: Saves data for both the user and the server, especially important for users on limited data plans.
  4. 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:

  1. Initially, don’t put the video source in the src attribute. Use data-src instead.
  2. Use the poster attribute to show a placeholder image.
  3. Use Intersection Observer to watch the video element.
  4. When the video element is about to enter the viewport, swap data-src to src 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:

  1. Optimize: Use TinyVid to drastically reduce video file size without losing quality.
  2. 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.

Optimize your videos like a pro

Use our free online video compression tool to reduce file size while maintaining quality.

Related Articles

View all articles

1 shared topic

How TinyVid.io Prioritizes Your Privacy: Secure Browser-Based Video Compression

Discover TinyVid.io's commitment to user privacy. Our video compression happens entirely on your device, meaning your files are never uploaded or stored on our servers.

1 shared topic

What Are the Instagram Video Specs for 2025? A Complete Guide

Your one-stop guide to the latest Instagram video specifications for 2025. We cover everything you need to know about format, resolution, aspect ratio, file size, and compression for Reels, Stories, and Feed videos.