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);
}
});
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();
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);
}
});
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With