Michael Heimes
Michael Heimes

Reputation: 43

Prevent iframe from loading on mobile

I am working on my portfolio page and I want to have my projects in a demo mode where the user can preview the sites in different viewports. I got the idea from here: http://my.studiopress.com/themes/genesis/#demo-full

On mobile devices I would like to keep the iframes from loading, and instead have links to the projects open the sites in the new tab.

If I have the divs containing the iframes hidden at the very top of my CSS file with display:none, I can see the iframes still load in the background and the page takes a long time to load.

Is there any way to keep them from loading at all when on a certain device or viewport size?

Upvotes: 2

Views: 4457

Answers (2)

Lewis Sherlock
Lewis Sherlock

Reputation: 1

A better solution is to approach this in reverse.

IE do not load the src to begin with by placing your URL in a attribute like 'data-src' for example.

See my code for this below. You simply copy the data-src to your src when your device, or device width is not mobile/mobile size.

I believe this is the best solution because there are no uncertainties. With the previously mentioned solutions (which I tried) you are racing against the clock with the browser for when your code runs and it decides to load the iframe src.

if(device !== true) {
  // add '#' to the href
  let iframe = document.getElementById('3dExperience')
  iframe.src = iframe.getAttribute('data-src')
}

Note: 'device' is the is-mobile npm package for detecting mobile.

Upvotes: 0

sepiott
sepiott

Reputation: 610

You could achieve this by using JavaScript and the HTML Data-Attribut. By setting the src-Attribute to something like "#" it won't load anything. You can use the data-Attribute to store the URL for use with JavaScript.

<iframe src="#" data-src="https://placekitten.com/200/300" frameborder="0"></iframe>

Then you just check to screen size with window.matchMedia() and set the src-attribute at a specific screen size.

var $iframe = $('iframe'),
    src = $iframe.data('src');

if (window.matchMedia("(min-width: 480px)").matches) {
    $iframe.attr('src', src);
}

Here is a working example: https://jsfiddle.net/5LnjL3uc/

If you want to show the iframe after a user resizes the window you need to put your code into a function and bind it to a resize event:

var $iframe = $('iframe'),
    src = $iframe.data('src');

function showIframe() {
    if (window.matchMedia("(min-width: 480px)").matches) {
        $iframe.attr('src', src);
    }
}

$(window).on('resize', showIframe);

// Initialize it once on document ready
showIframe();

Working Example: https://jsfiddle.net/5LnjL3uc/1/

Upvotes: 9

Related Questions