Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}

});
like image 936
skinnysuit Avatar asked Jun 04 '14 00:06

skinnysuit


3 Answers

I was trying to do the same thing, after some cross browser testing I found that adding the 'autoplay' attribute dynamically didn't work consistently

( Fine in Firefox, not at all in IE(10), only on document ready / not on resize in Chrome )

So to get it working as expected, instead of

$('video').attr('autoplay', true);

I used

$('video')[0].play();
like image 132
00-BBB Avatar answered Sep 19 '22 01:09

00-BBB


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);
        }
    });
});
like image 28
Alfred Huang Avatar answered Sep 22 '22 01:09

Alfred Huang


Recent versions of iOS and Android will not Autoplay videos. They must be started via user interaction.

This has been implemented to avoid users blowing bandwidth limits they may have with their mobile carriers.

The solution, therefore, is to show/hide play controls depending upon the screen widths.

In addition, to avoid unnecessary downloads, you should consider not showing the video at all, and displaying a fallback image or even displaying nothing, if the video does not significantly add to the user experience.

like image 38
Colin Irwin Avatar answered Sep 18 '22 01:09

Colin Irwin