prevent-videos-from-preloading-on-mobile | sahad sarang

Prevent Videos From Pre-loading On Mobile

The video looping background looks good on the first frame of the website. Normally the looping or autoplay videos come on the first fold of the website to give a short presentation of your products or services it will look good on the large screen especially.

The video with animations will be large size files that take time to load on small screen devices like mobiles phones. Most of the websites because of this heavy load on the speed they try to hide the videos on mobile screens and display images still issue will not get fix because normally developers hide the video on mobile screen using CSS which will still load the video on the background. 

How to fix this to improve the page speed of your website?

Developers can fix the issue using Jquery & Html Changes. Here’s how you have to do the changes.

From this

<video id="bgvideo" autoplay muted loop>
<source src="video.mp4" type="video/mp4">
</video>

To this

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

After that, add this 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 bgvid = jQuery('#bgvideo');
 
    if (bgvid.is(':visible')) {
      jQuery('source', bgvid).each(
        function() {
          var el = jQuery(this);
          el.attr('src', el.data('src'));
        }
      );
 
      bgvid[0].load();
    }
  }
)

Done. now the video will not load on the small screen mobile devices page speed issue will get resolved.

Leave a Reply

Your email address will not be published. Required fields are marked *