Dave Bud
Dave Bud

Reputation: 41

CSS Display: none a better solution?

I am using DIVI, Wordpress and I have this video I set as a background for Desktop but I disable it for Mobile and Tablets but here's the thing, what the Disable option does is just a display:none so the video is still being loaded DOM.

Is there a way to totally block an object from loading? so it does affect the loading time on mobile devices?

Share your thoughts, Please

Upvotes: 1

Views: 121

Answers (2)

Dierig Patrick
Dierig Patrick

Reputation: 186

Based on the suggestions Ian kindly made, here is my working solution.

Firstly, I changed each video's child source elements to have an attribute data-src like so:

<video id="my-id">    
   <source data-src="somevideo.mp4">
</video>

Then, after performing a mobile check using the script available at http://detectmobilebrowsers.com/ which I modified to include iPads etc (related SO answer here) I simply used the following script to automatically update the src attribute of each video (if we're on desktop in my case):

var sources = document.querySelectorAll('video#my-id source');
// Define the video object this source is contained inside
var video = document.querySelector('video#my-id');
for(var i = 0; i<sources.length;i++) {
  sources[i].setAttribute('src', sources[i].getAttribute('data-src'));
}
// If for some reason we do want to load the video after, for desktop as opposed to mobile (I'd imagine), use videojs API to load
video.load(); 

And that's it! Nothing loads on mobile devices anymore and I can have fairly granular control over the devices it will or won't load on.

Hope this helps somebody.

Upvotes: 0

Martijn
Martijn

Reputation: 16103

Yes, flip your logic:

Never load the clip, unless it's a capable device.

You can use javascript to check if the screen width is broad enough (or even better: Check if the device is capable of your clip, some tablets in a wifi can often display it as well).
If you decide it can be played, add a video element to the page (or add the src to your element) and trigger a play event.

BTW: This trick can be applied to many resources, eg images as well.

Upvotes: 2

Related Questions