Daniel Lynch Daniel Lynch - 5 months ago 50
CSS Question

Disable html5 video download at CSS breakpoint

I have a short looping html5 video that plays automatically in the browser. When the browser width is reduced to 870px the video disappears thanks to a css media query and display:none;

How do I ensure the video does not download if the window starts at a smaller size like on a mobile device?

The video is 1.8mb and I don't want to unnecessarily tax my user's data usage. Thanks!

<video id="video_background" preload="none" autoplay="false" loop="loop" muted="muted" volume="0">
<source src="video/creativeishappening.mp4" type="video/mp4">
Video not supported
</video>





$(function() {

// onload
if(document.body.clientWidth >= 870) {
$('video').attr('autoplay', true);
}

});

Answer

Your video playing automatically is due to the "autoplay" attribute in the tag.

So you want the video autoplay depending on the window size when loaded. So you can add the attribute manually, like below:

$(function() {

    // onload
    if(document.body.clientWidth >= 870) {
        $('video').attr('autoplay', true);
    }

    // If you want to autoplay when the window is resized wider than 780px 
    // after load, you can add this:

    $(window).resize(function() {
        if(document.body.clientWidth >= 870) {
            $('video').attr('autoplay', true);
        }
    });
});