Lazy loading video

Published: August 16, 2019

As with image elements, you may also want to lazy-load video. Videos are commonly loaded with the <video> element, though for videos hosted on other services such as YouTube they may use <iframe>s (in which case check out the article in lazy-loading iframes).

How to lazy-load <video> depends on the use case, as there are a couple of different solutions.

For video that doesn't autoplay

Avoiding autoplaying videos is usually best practice as it leaves the control with the user. In these cases specifying the preload attribute on the <video> element is the best way to avoid loading the whole video:

<video controls preload="none" poster="one-does-not-simply-placeholder.jpg">
  <source src="one-does-not-simply.webm" type="video/webm">
  <source src="one-does-not-simply.mp4" type="video/mp4">
</video>

The previous example uses a preload attribute with a value of none to prevent browsers from preloading any video data. The poster attribute gives the <video> element a placeholder that will occupy the space while the video loads.

In most browsers preload defaults to metadata and a portion of the video is preloaded using the Content-Range header. This can result in more data being downloaded than desired—particularly if the Content-Range header is not supported by the browser. Even when this is supported, browsers cannot know what bytes the metadata is stored at, and it may not be stored at the beginning of the file. Therefore, the best chance of avoiding loading the video is in specifying none and using preload="none".

This can be further enhanced to preload the metadata when the user hovers the video with an onmouseenter attribute (or with the equivalent mouseenter event handler):

<video controls
  preload="none"
  poster="one-does-not-simply-placeholder.jpg"
  onmouseenter="event.target.setAttribute('preload','metadata')">
  <source src="one-does-not-simply.webm" type="video/webm">
  <source src="one-does-not-simply.mp4" type="video/mp4">
</video>

This not only reduces the delay when the user goes to play the video, but also shows the duration of the video as soon as they.

Videos can qualify as an LCP candidates. A poster image will be quicker to load than the video so where this is an LCP candidate, you should use a poster image, but also preload it with a fetchpriority attribute value of "high":

<link rel="preload" href="one-does-not-simply-placeholder.jpg" as="image" fetchpriority="high">
<video controls preload="none"
  poster="one-does-not-simply-placeholder.jpg"
  onmouseenter="event.target.setAttribute('preload','metadata')">
  <source src="one-does-not-simply.webm" type="video/webm">
  <source src="one-does-not-simply.mp4" type="video/mp4">
</video>

For video acting as an animated GIF replacement

Autoplaying videos are most commonly used for GIF-style quick animations. While animated GIFs enjoy wide use, they're subpar to video equivalents in a number of ways, particularly in file size. Animated GIFs can stretch into the range of several megabytes of data. Videos of similar visual quality tend to be far smaller.

Using the <video> element as a replacement for animated GIF is not as straightforward as the <img> element. Animated GIFs have three characteristics:

  1. They play automatically when loaded.
  2. They loop continuously (though that's not always the case).
  3. They don't have an audio track.

Achieving this with the <video> element looks something like this:

<video autoplay muted loop playsinline>
  <source src="one-does-not-simply.webm" type="video/webm">
  <source src="one-does-not-simply.mp4" type="video/mp4">
</video>

The autoplay, muted, and loop attributes are self-explanatory. playsinline is necessary for autoplaying to occur in iOS. Now you have a serviceable video-as-GIF replacement that works across platforms. But how to go about lazy loading it? To start, modify your <video> markup accordingly:

<video class="lazy" autoplay muted loop playsinline width="610" height="254" poster="one-does-not-simply.jpg">
  <source data-src="one-does-not-simply.webm" type="video/webm">
  <source data-src="one-does-not-simply.mp4" type="video/mp4">
</video>

You'll notice the addition of the poster attribute, which lets you specify a placeholder to occupy the <video> element's space until the video is lazy-loaded. As with the <img> lazy-loading examples, stash the video URL in the data-src attribute on each <source> element. From there, use JavaScript code similar to the Intersection Observer-based image lazy loading examples:

document.addEventListener("DOMContentLoaded", function() {
  var lazyVideos = [].slice.call(document.querySelectorAll("video.lazy"));

  if ("IntersectionObserver" in window) {
    var lazyVideoObserver = new IntersectionObserver(function(entries, observer) {
      entries.forEach(function(video) {
        if (video.isIntersecting) {
          for (var source in video.target.children) {
            var videoSource = video.target.children[source];
            if (typeof videoSource.tagName === "string" && videoSource.tagName === "SOURCE") {
              videoSource.src = videoSource.dataset.src;
            }
          }

          video.target.load();
          video.target.classList.remove("lazy");
          lazyVideoObserver.unobserve(video.target);
        }
      });
    });

    lazyVideos.forEach(function(lazyVideo) {
      lazyVideoObserver.observe(lazyVideo);
    });
  }
});

When you lazy-load a <video> element, you need to iterate through all of the child <source> elements and flip their data-src attributes to src attributes. Once you've done that, you need to trigger loading of the video by calling the element's load method, after which the media will begin playing automatically per the autoplay attribute.

Using this method, you have a video solution that emulates animated GIF behavior, but doesn't incur the same intensive data usage as animated GIFs do, and you can lazy-load that content.

Lazy loading libraries

The following libraries can help you to lazy-load video:

  • vanilla-lazyload and lozad.js are super lightweight options that use Intersection Observer only. As such, they are highly performant, but will need to be polyfilled before you can use them on older browsers.
  • yall.js is a library that uses Intersection Observer and falls back to event handlers. It can also lazy load video poster images using a data-poster attribute.
  • If you need a React-specific lazy loading library, you might considerreact-lazyload. While it doesn't use Intersection Observer, it does provide a familiar method of lazy loading images for those accustomed to developing applications with React.

Each of these lazy loading libraries is well documented, with plenty of markup patterns for your various lazy loading endeavors.