Prevent Background Videos From Pre-Loading On Mobile


About The Author
Cabe Nolan is the founder of WP Cover where he shares his insight into WordPress, development, & entrepreneurship. Outside of WPCover, Cabe continues to run a successful WordPress development firm, Bold City Design as well as a few high profile websites, Arrivala, Two Way Resume, Dock Skipper, and a successful outdoors brand, DolfinPack.







Prevent Background Videos From Pre-Loading On Mobile

Background looping videos have become very popular over the last couple years.  They look fantastic, are very engaging, and a nice way to differentiate your company or business from competitors.

The downside to the looping videos is they can be fairly large video files and they don’t work on mobile devices.  Most developers understand this and will simply hide the video using CSS on mobile and display an image instead.  However, many don’t know that in some cases the background video may still be pre-loading on mobile devices even though it is hidden.  How do you prevent this from happening?

Fortunately, we can fix this issue with some jQuery and simple HTML changes.  Here’s how we’re going to do it:

First, update your video src from:

<video id="bgvid" autoplay muted loop>
<source src="yourvideofileurl.mp4" type="video/mp4">
</div>

TO:

<video id="bgvid" autoplay muted loop>
<source data-src="yourvideofileurl.mp4" type="video/mp4">
</video>

Next, add some additional jQuery that will check if the video is visible. If so, it will swap the data-src element to the src element:

jQuery(
  function() {
    var bgv = jQuery('#bgvid');

    if (bgv.is(':visible')) {
      jQuery('source', bgv).each(
        function() {
          var el = jQuery(this);
          el.attr('src', el.data('src'));
        }
      );

      bgv[0].load();
    }
  }
)	

That’s all there is to it! Give it a go and let us know how it worked for you in the comments.


Share Your Thoughts

Leave a Reply

Your email address will not be published.


Related Stuff You Might Like







WordPress News, Tips, & Code Snippets

Join the WP Cover mailing list and get wordpress news, tips, code snippets, security warnings, and more delivered right to your inbox.  We won't flood your inbox, newsletters typically go out every 1-2 weeks unless it involves an important security release.

You have Successfully Subscribed!