Stop video from loading in background on mobile

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" />

Assuming you're setting visibility via CSS, or in earlier JS code, you can do something like this:

  • Include data-src attributes instead of src on your video elements. No src to load if we don't need to.
  • If visible, copy data-src to src
  • Now call .load() on the video element, to pick up the new values.
  • $(
      function() {
        var bgv = $('#bgvid');
    
        if (bgv.is(':visible')) {
          $('source', bgv).each(
            function() {
              var el = $(this);
              el.attr('src', el.data('src'));
            }
          );
    
          bgv[0].load();
        }
      }
    )
    .hidden-xs {
      display: none;
    }
    
    /* dummy criterion for demo purposes */
    @media screen and (min-width: 400px) {
      .hidden-xs {
        display: block;
      }
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <video id="bgvid" class="hidden-xs " controls>
      <source type="video/mp4" data-src="https://archive.org/download/UNIVAC-AD-2/UNIVAC2_512kb.mp4"></source>
      <source type="video/ogg" data-src="https://archive.org/download/UNIVAC-AD-2/UNIVAC2.ogv" />
    </video>

    Set <video> poster attribute value to path to image file. At load event of window check conditions to determine whether or not to set .src of <video> element to path to video file.

    <video poster="myimage.jpg"></video>
    

    window.onload = function() {
      if (/* conditions */ window.innerWidth > 480) 
        document.querySelector("video").src = "myvideo.mp4";
    }
    
    链接地址: http://www.djcxy.com/p/83586.html

    上一篇: 基于滚动淡入/淡出div

    下一篇: 停止在移动设备上加载背景视频