Guide to lazy loading HTML videos for your website

November 22, 2024
8 minutes
Video Player
Jump to
Share
This is some text inside of a div block.

Lazy loading is a highly effective web performance strategy that postpones the loading of non-essential media like images and videos until they’re required. By prioritizing critical content first, lazy loading helps reduce initial page load times, ensuring users can access essential information faster and experience a more seamless interface.

For videos, this technique triggers loading only when users scroll to or interact with the media, conserving bandwidth and making the page feel faster and more responsive. It’s especially valuable for mobile users or those on slower connections, where optimizing resource usage directly translates into a smoother, more enjoyable browsing experience.

Why lazy load videos?

1. Faster loading and better performance

Videos are among the heaviest assets on a web page, significantly increasing load times if not managed effectively. By deferring their loading until they're needed, lazy loading prioritizes visible, essential content first. This approach ensures the initial page load is faster and smoother, especially for users on slower connections or older devices.

2. Better user experience

Lazy loading contributes to a seamless browsing experience by reducing the likelihood of auto playing or buffering videos disrupting user interactions. Visitors can access text, images, and other critical elements without delay, ensuring they engage with content at their own pace. For videos further down the page, users only download them when they scroll or interact, leading to a more natural and distraction-free interface.

3. Bandwidth optimization

High-resolution videos consume significant bandwidth, which can be a challenge for users on limited data plans or slower networks. Lazy loading ensures that video files are only downloaded when requested, conserving data and providing a more user-friendly experience. This strategy also reduces hosting costs for website owners by limiting unnecessary resource usage.

4. SEO advantages

Search engines prioritize fast-loading websites, and lazy loading directly impacts key performance metrics like:

  • Largest Contentful Paint (LCP): Measures how quickly the largest visible content (like text or images) loads.
  • Cumulative Layout Shift (CLS): Evaluates page stability by penalizing content that shifts during loading.

By deferring non-critical video content, lazy loading improves these metrics, leading to higher search rankings and better discoverability. Additionally, faster load times and reduced page weight contribute to overall site performance, which aligns with modern SEO best practices.

How lazy loading works

Lazy loading for videos is a technique that delays the loading of the actual video file until it’s necessary usually when the user scrolls down to the video or interacts with it. By holding off on loading the video until it’s in view or actively requested, we save bandwidth and improve loading speeds for the parts of the page users are interacting with immediately. Here are the two main components involved in lazy loading videos:

1. Data attributes

  • What they are: Data attributes are custom attributes added to HTML elements that store additional information about the element. They are prefixed with data-, such as data-src or data-poster.
  • How they work in lazy loading: For lazy loading, we use data attributes like data-src to hold the URL of the video file without initiating its download. This way, the browser doesn't load the video until we explicitly tell it to. The data-src attribute acts as a placeholder for the actual src attribute.

1<video width="640" height="360" controls preload="none" data-src="path-to-video.mp4" poster="path-to-thumbnail.jpg"> 
2	<!-- Your browser does not support the video tag. -->
3</video> 

In this example, the video file (path-to-video.mp4) is stored in data-src instead of src, preventing it from loading right away. The poster attribute displays a thumbnail or placeholder image in place of the video, letting users see where the video is on the page without downloading the video itself.

2. Intersection Observer API

  • What it is: The Intersection Observer API is a powerful, efficient JavaScript API that allows you to track when an element (like a video) enters or exits the viewport. In other words, it lets you monitor when an element becomes visible on the user’s screen.
  • How it works in lazy loading: The Intersection Observer watches for the video to enter the viewport. When the video appears on the screen, the observer triggers an action to replace the data-src attribute with src, loading the video at that moment. This prevents videos from loading while they’re offscreen and unused.

Example code using Intersection Observer:

1document.addEventListener("DOMContentLoaded", function () { 
2  const videos = document.querySelectorAll("video[data-src]"); 
3    if ("IntersectionObserver" in window) { 
4    const observer = new IntersectionObserver((entries, observer) => { 
5    entries.forEach(entry => { 
6      if (entry.isIntersecting) { 
7        const video = entry.target; 
8        video.src = video.getAttribute("data-src"); // Move URL from data-src to src 
9        video.load(); // Trigger video loading 
10      observer.unobserve(video); // Stop observing this video as it’s now loaded 
11    } 
12    }); 
13  });
14  videos.forEach(video => observer.observe(video)); 
15  } 
16}); 

Explanation of the code:

  • We start by selecting all video elements with a data-src attribute.
  • We check if the browser supports Intersection Observer (it’s widely supported in modern browsers).
  • An Intersection Observer instance is created, with a callback function that executes whenever a watched element (in this case, a video) enters or exits the viewport.
  • When a video enters the viewport (entry.isIntersecting), we transfer the video URL from data-src to src and call video.load() to start downloading it.
  • Once the video loads, we stop observing it with observer.unobserve(video) to save resources.

Let’s dive into the steps for lazy loading a video!

Step 1: Setting up the HTML structure with placeholder attributes

  • Use data-src instead of src in your <video> tag to store the actual video URL without loading it. Add a poster attribute with a thumbnail or image to show as a placeholder for the video, letting users know a video is available there.

HTML Example:

1<video width="640" height="360" controls preload="none" data-src="video.mp4" poster="thumbnail.jpg"> 
2	<!-- Your browser does not support the video tag. -->
3</video> 

Step 2: Using Intersection Observer to watch for visibility

  • Use JavaScript and the Intersection Observer API to detect when a video is scrolled into view. When the observer detects the video entering the viewport, it updates the src attribute and initiates video loading.
  • This approach makes sure that videos load only when they’re about to be watched, reducing initial page load times.

Step 3: Optional - load on interaction (click-to-play)

  • If you want videos to load only on user interaction (like when they click play), you can add a click event listener. This way, the video loads and plays only when users actively engage with it.

1document.querySelectorAll("video[data-src]").forEach(video => { 
2  video.addEventListener("play", function () { 
3    if (!video.src) { 
4      video.src = video.dataset.src; 
5      video.load(); 
6    } 
7  }, { once: true }); // Event will run once and then stop listening 
8}); 

Step 4: Additional optimizations (advanced)

  • Lower resolutions for mobile: Serve different video resolutions based on screen size by setting various data-src values for mobile and desktop.
  • Video compression: Compress videos using efficient codecs like H.265 or VP9 to improve load speeds without sacrificing quality.
  • Adaptive streaming: Use adaptive streaming (e.g., HLS) to deliver video in smaller, network-optimized chunks.
  • Modern image formats for posters: Use formats like WebP or AVIF for poster images to further reduce file size.

Advanced techniques for optimizing video performance

1. Use lower-resolution videos for mobile

Use responsive video techniques to serve different resolutions based on device size or network conditions. For example, set different data-src values for mobile vs. desktop devices.

2. Compress videos for faster loading

Optimize video file size with codecs like H.265 or VP9 for better compression without sacrificing quality. Tools like HandBrake, FFmpeg, or online compressors can help.

3. Consider using adaptive streaming (e.g., HLS)

With adaptive streaming protocols (like HLS or MPEG-DASH), you can serve videos in smaller chunks that adjust quality based on the user’s connection, improving load times and reducing buffering. HLS is widely supported across modern browsers and particularly useful for longer videos.

4. Use WebP or AVIF formats for poster images

Modern image formats like WebP or AVIF offer better compression rates for poster images, reducing the data size even further.

5. Optimize preloading strategy

If you want to preload a video slightly ahead of when it’s needed (but not immediately on page load), you can configure the Intersection Observer threshold or use a timeout. This way, videos will be preloaded only moments before they enter the viewport.

Lazy loading best practices

  1. Use preload strategically: Setting preload="none" on <video> elements ensures they don’t start downloading until required.
  1. Prioritize mobile users: Data is more limited on mobile, so ensure that lazy loading is optimized for smaller screens and mobile networks.
  1. Test your implementation: Always test lazy loading on various devices and network speeds to ensure that the video loads smoothly and is triggered at the right time.

Testing and debugging lazy loading implementations

When testing lazy loading, pay attention to these areas:

  1. Check load times with developer tools: Use Chrome DevTools to monitor load times and see when videos are loaded. Ensure that videos only start loading when they are supposed to.
  2. Simulate slow network conditions: In Chrome DevTools, you can throttle the network to simulate slow connections. Ensure that lazy loading behaves correctly in low-bandwidth environments.
  3. Test on different devices: Lazy loading may perform differently on mobile vs. desktop. Ensure that videos load seamlessly on both.
  4. Use Lighthouse or PageSpeed insights: Both tools will give you insight into load times, LCP, and other performance metrics that affect user experience and SEO.

Tools and libraries for lazy loading

Several JavaScript libraries offer built-in lazy loading, including:

  • LazyLoad.js: A small, fast JavaScript library for lazy loading images, Iframes, and videos.
  • lozad.js: A highly performant, lightweight lazy loader optimized for Intersection Observer.
  • lazysizes: Supports responsive images and videos with additional options for low-power devices and can be highly customized.

These libraries simplify lazy loading and come with additional options for optimization.

Summary

By loading videos only when they are needed, websites can prioritize the most important content, ensuring a faster, smoother experience for users, especially on mobile devices or slower networks.

In FastPix-player, lazy loading is implemented efficiently using the Intersection Observer API, a powerful tool for detecting when a video enters the viewport. This allows the player to delay loading until the video becomes visible on the user's screen, minimizing unnecessary resource usage and improving page performance.

Here’s a recap of the key benefits of lazy loading:

Intersection Observer for efficient video loading

The Intersection Observer is the best way to detect when a video enters the viewport. This technique ensures that videos are loaded only when they are visible to the user, reducing initial page load times and conserving bandwidth. For FastPix-player, this approach ensures videos aren’t prematurely loaded, which means faster page rendering and better performance.

Data attributes for storing video sources

By utilizing data-src attributes, FastPix-player stores the video source without loading it upfront. This prevents unnecessary video downloads and helps manage resources more efficiently. The video will only load once it’s visible on the screen, which optimizes page load times.

Event-Based loading (e.g., play-on-click)

Another useful approach is event-based loading, such as loading videos only when a user clicks the play button. While FastPix-player currently uses Intersection Observer for efficient lazy loading, event-based triggers like play-on-click can be useful for enhancing control over when the video is loaded, especially for non-autoplay videos. This feature adds a layer of user control while optimizing loading further.

By integrating these lazy loading strategies into FastPix-player, you can drastically improve the performance of your site, especially on pages that contain multiple video elements. Lazy loading reduces bandwidth usage, improves SEO scores, and enhances the overall user experience by ensuring that videos only load when they’re needed, without impacting the rest of the page’s performance.

FAQs

What is lazy loading for videos?
Lazy loading for videos is a technique that delays the loading of video files until they are needed—usually when the user scrolls to or interacts with the video. This helps improve page load times and reduces unnecessary bandwidth consumption by loading videos only when they become visible.

How does lazy loading improve website performance?

Lazy loading improves website performance by deferring the loading of non-essential resources (like videos) until they are needed. This reduces initial page load times, conserves bandwidth, and allows users to access essential content faster, especially on slower connections or mobile devices.

Why should I lazy load videos on my website?

Lazy loading videos helps improve the user experience by reducing buffering times, conserving bandwidth, and speeding up page load times. It also improves SEO metrics like Largest Contentful Paint (LCP) and Cumulative Layout Shift (CLS), which can boost your search engine ranking.

Will lazy loading affect SEO?

Yes, lazy loading can positively impact SEO by improving page load speeds, reducing initial resource loading times, and enhancing key performance metrics such as LCP and CLS. This, in turn, can lead to better search engine rankings and improved discoverability.

Start Live Streaming for free

Enjoyed reading? You might also like

Try FastPix today!

FastPix grows with you – from startups to growth stage and beyond.