CaribouCode
CaribouCode

Reputation: 14428

HTML video autoplaying on mobile

I have an video embedded in my HTML like so:

<video autoplay loop data-hidden="xs">
  <source src="video.webm" type="video/webm">
  <source src="video.mp4" type="video/mp4">
</video>

Works a treat. But now consider the following CSS applied (notice the [data-hidden] attribute module on the video tag):

@media (max-width: 767px) {
  [data-hidden~="xs"] { display: none !important }
}

Now, on mobile devices, the video should have display: none!important;. This works as expected, however I'm finding sometimes the autoplay attribute on the video DOES kick in and the video starts playing automatically when I load the page, even though the video tag is set to display none. How can I avoid this?

Is there a better way to do this all together? I don't really want the video loading at all on mobiles as it will obviously slow down the site.

Upvotes: 1

Views: 986

Answers (1)

Tim
Tim

Reputation: 807

Display:none is fine, but the best way to do it in my personal opinion is using an If-statement in whatever server-side lingo you're using. That will stop the HTML from rendering entirely (Rather than just hiding it like CSS does) if viewed on mobile.

For example, here's a semi-pseudo (Probably works but not tested) PHP snippet that would perform this:

function CheckMobile() {
    return preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]);
}

if(CheckMobile()){
   continue;
}
else{
<video autoplay loop data-hidden="xs">
  <source src="video.webm" type="video/webm">
  <source src="video.mp4" type="video/mp4">
</video>
}

This is basically saying, unless the user is not on a mobile browser, don't bother showing them the video tag.

Like I said, I've not tested the snippet above, so it may or may not work, but you get the gist.

Upvotes: 1

Related Questions