阻止iframe在移动设备上加载 [英] Prevent iframe from loading on mobile

查看:94
本文介绍了阻止iframe在移动设备上加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的投资组合页面上工作,我想让我的项目处于演示模式,在该模式下,用户可以在不同视口中预览网站.我从这里得到了这个主意: http://my.studiopress.com/themes/genesis/#demo-full

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

在移动设备上,我希望不加载iframe,而是使用指向项目的链接在新标签页中打开网站.

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.

如果在我的CSS文件的顶部使用display:none隐藏了包含iframe的div,则可以看到iframe仍在后台加载,并且该页面需要很长时间才能加载.

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?

推荐答案

您可以通过使用JavaScript和HTML数据属性来实现.通过将src-Attribute设置为#"之类的内容,将不会加载任何内容.您可以使用data-Attribute存储用于JavaScript的URL.

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>

然后,您只需使用window.matchMedia()检查屏幕大小,然后将src属性设置为特定的屏幕大小即可.

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);
}

这是一个有效的示例: https://jsfiddle.net/5LnjL3uc/

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

如果要在用户调整窗口大小后显示iframe,则需要将代码放入函数并将其绑定到调整大小事件:

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();

工作示例: https://jsfiddle.net/5LnjL3uc/1/

这篇关于阻止iframe在移动设备上加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆