Disable html5 video download at CSS breakpoint

最后都变了- 提交于 2019-12-20 23:32:13

问题


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

});

回答1:


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



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/24027202/disable-html5-video-download-at-css-breakpoint

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!