Lazy loading video

Lazy loading is a technique where content is loaded only when it’s needed or when it comes into the viewport. This can significantly improve page load times, reduce initial page weight, and save bandwidth.

Lazy loading videos

Just as with images, videos can also be lazy-loaded. Videos are typically loaded using the <video> element, but there are different scenarios and methods to consider:

Video that doesn’t autoplay

If the video playback is initiated by the user (i.e., videos that don’t autoplay), you might want to use the preload attribute on the <video> element.

<video controls preload="none" poster="video.jpg">
<source src="video.webm" type="video/webm">
<source src="video.mp4" type="video/mp4">
</video>

The preload attribute with a value of “none” prevents browsers from preloading any video data. The poster attribute provides a placeholder for the video while it loads.

Video acting as an animated GIF replacement

Animated GIFs, though popular, can be large in size. Using the <video> element as a replacement can offer similar visual quality with a much smaller file size.

To achieve this, use the following attributes: autoplay, muted, loop, and playsinline.

<video autoplay muted loop playsinline>
<source src="video.webm" type="video/webm">
<source src="video.mp4" type="video/mp4">
</video>

To lazy-load such videos, modify the <video> markup and use JavaScript with the Intersection Observer API to detect when the video comes into the viewport and then load it.