Stop video from loading in background on mobile

Viewed 11133

I have a video header that I only want to play on desktop, with a static image header on mobile. I can hide the video on mobile and it looks like it works fine, but the video is still being loaded in the background and slowing the page load. How can I stop the video from loading at all on mobile.

<video id="bgvid" class="hidden-xs ">    
  <source type="video/mp4" src="myvideo.mp4"></source>
</video>

<img alt="" style="width: 100%; height: auto;" src="myimage.jpg" class="visible-xs" />
4 Answers

This solution works for me. You can change the number "767" to any maximum pixel width of a device you would like the video not to display on. Keep in mind that this will remove all videos from mobile devices. However, you can also use a class or ID of the video tag; you just need to change the script for remove().

Script code in header:

<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script> 
 $(document).ready(function() {
   if($(window).width() <= 767){

    $( "video" ).remove();
   }
});

</script>

In Body of Document:

<div class="fullscreen-bg">
    <video loop muted autoplay class="fullscreen-bg__video">
            <source src="http://yoururl.com/video.mp4" type="video/mp4">
        </video>

</div>

If you want to stop multiple videos and mute them as well with fallback img on mobile this should help out

const video = document.querySelectorAll('video')
              video.forEach(data=>{
                data.volume = 0 //mute video
                console.log(data);
                  if (window.innerWidth <= 768) {
                      data.autoplay=false;
                  } else {
                      data.play();
                  }
                }) 

Related