10

EXPLANATION: A customer of mine wants to have a background video running on his responsive website. However he would also like to remove it for tablet/mobile users. I know this can be done with media queries, but the video would still load as part of the DOM and that is what i would like to prevent.

QUESTIONS:

  1. Can the video element be removed using JavaScript/jQuery from the DOM when it loads view-port at certain widths?

  2. Can the same video be recovered when if the view port is manually increased in with? (i suspect this is a bad approach)

  3. Will a video with "display:none;" still affect loading/battery time on a tablet/mobile ?

Thanks you for you assistance.

user3812110
  • 111
  • 1
  • 1
  • 6
  • 1
    Welcome to Stack Overflow. Please read [Stack Overflow: How to ask](http://stackoverflow.com/questions/how-to-ask) and [Jon Skeet's Question Checklist](http://msmvps.com/blogs/jon_skeet/archive/2012/11/24/stack-overflow-question-checklist.aspx) to find out how to ask a good question that will generate good useful, answers. – Our Man in Bananas Jul 07 '14 at 11:33

4 Answers4

2

See this answer to detect if you're on a mobile device.

Then, using this test, you can .hide() your element using jQuery, or set its src attribute to "", to be sure it's not downloading.

Community
  • 1
  • 1
Jb Drucker
  • 972
  • 8
  • 14
2

Based on mobile dimensions use $('video').remove(). this will removes the DOM element from webpage. so it will not render in html.

maskacovnik
  • 3,080
  • 5
  • 20
  • 26
1

not sure if this might help but this snippet will stop video getting played on mobile devices also you can mute the audio here and it should show fallback img here.

const video = document.querySelectorAll('video')
              video.forEach(data=>{
                data.volume = 0 //mute audio
                console.log(data);
                  if (window.innerWidth <= 768) {
                      
                      data.autoplay=false; or //data.remove()
                  } else {
                      data.play();
                  }
                }) 
  • The post mentioned they want to avoid loading the video entirely - "but the video would still load as part of the DOM and that is what i would like to prevent." – kjones Jul 29 '21 at 22:56
  • data.remove() will totally remove the video element then we will need to add fallback img for that though – Being Explorer Jul 30 '21 at 11:30
0

You could also use css. This is much easier.

@media only screen 
  and (min-device-width: 320px) 
  and (max-device-width: 480px)
  and (-webkit-min-device-pixel-ratio: 2) {
    video {
        display:none;
    }
}

Then have an image with a negative z-index, that way when the video is not displayed, the image will appear.

Anton Koenig
  • 39
  • 1
  • 11