In my project I’m using iframes to load and autoplay videos from Vimeo. That’s great for desktop, but pretty uncool for mobile, since I just discovered that even if your element is set to “display: none”, mobile browsers WILL load it.
That means that on mobile, my page can take up to 30-40 seconds to fully load + it’s like 45MB heavy. And that’s crazy.
So, I need a way to somehow NOT load the iframe on mobile. How can I do that?
I tried using this script to detect screen size and remove the “src” attribute, but it’s not working for some reason.
<script>
if (window.matchMedia("(max-width: 997px)").matches) {
document.getElementById("video-hover").removeAttribute("src");
}
</script>
if you’re using the vimeo player API, you could setup two different kind of options to conditionally pass into the payer constructor. One option would have the autoplay: true an the other option would have the autopay: false.
Could look something like this:
document.addEventListener('DOMContentLoaded', (event) => {
initVideoInjection();
});
function initVideoInjection() {
// checks width of the device
let WindowWidth =
window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth;
// options for desktop
let optionsDesktop = {
id: {"your_vimeo_video_id"},
autoplay: true,
loop: true,
muted: true
};
// options for mobile
let optionsMobile = {
id: {"your_vimeo_video_id"},
autoplay: false
};
if (WindowWidth < 997) {
// player constructor mobile
let player = new Vimeo.Player(your_empty_vimeo_div, optionsMobile);
} else {
// player constructor desktop
let player = new Vimeo.Player(your_empty_vimeo_div, optionsDesktop);
}
}
Hey @anthonysalamin, thanks for your answer. I’m not very knowledgeable when it comes to JavaScript and I’m not using the Vimeo Player API. I took a quick look at their page and it seems easy enough to call it and use it.
I do have a couple of questions that stem from my limited JavaScript knowledge:
I actually have multiple videos embedded from Vimeo. They can’t have the same ID, so do I need to set different IDs and call each of them individually in **id: {"your_vimeo_video_id} **?
I kind of don’t understand the need for let player = new Vimeo.Player(your_empty_vimeo_div, optionsDesktop);. Is your_empty_vimeo_div supposed to be just an empty div with that id?
Well if you have multiple video on your document, you first need to find them all, store them in an array, loop through that array to get every ID of the videos then pass that variable into the player option.
Simply add a class="lazyload" to your iframe
…and reference to the lazysizes script like so: <script>https://cdnjs.cloudflare.com/ajax/libs/lazysizes/4.1.8/lazysizes.min.js</script>
more infos:
Here is another way to defer iframes or videos, have a look: