Lazy loading videos when using autoplay

Web development involves walking a tightrope when it comes to how much you want to add visually. On the one hand, you want your site to load as fast as possible, and on the other you want it to be visually striking. It often strikes me funny to see people focusing heavily on minifying their CSS and Javascript, while having huge images all over the same site.

On our site we’ve made use of the VIDEO tag in two locations: the home page, and the “Featured Work” page. We wanted to be able to show video previews of sites we’ve created, without slowing the pages down. This is fairly easy with the ‘preload=”none”‘ attribute which tells the video to load as-needed, rather than during the initial page load. The downside to this approach is that using the “autoplay” attribute will automatically negate our preload choice and the video will be included in the initial loading of the page. Since we wanted the videos to play automatically, we needed a work around.

The best solution for us was to create thumbnail images of each site, and add them to the videos using the “poster” attribute:

<video class="project-video" muted loop preload="none" poster="[poster-url-here]">
    <source src="[video-url-here]" type="[video-format-here]">
</video>

Then, once the page is done loading, then we can start activating the videos using their “play” method in Javascript:

$(window).on('load', function() {
    $('.project-video').each(function() {
        $(this).get(0).play();
    });
});

Now we have functionality like autoplay, but without having to load the videos first.

In our case, you don’t see these these videos until you activate their parent modal div.