防止在移动设备上加载iframe

问题描述 投票:0回答:2

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

在移动设备上,我想保留iframe加载,而是有项目链接打开新标签中的网站。

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

在特定设备或视口大小时,有没有办法阻止它们加载?

javascript jquery iframe mobile
2个回答
4
投票

您可以使用JavaScript和HTML Data-Attribut实现此目的。通过将src-Attribute设置为类似“#”的内容,它将不会加载任何内容。您可以使用data-Attribute存储用于JavaScript的URL。

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

然后,您只需使用window.matchMedia()检查屏幕大小,并将src-attribute设置为特定的屏幕大小。

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

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

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

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

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/


0
投票

更好的解决方案是反过来解决这个问题。

IE不会通过将URL放在像“data-src”这样的属性中来加载src。

请参阅下面的代码。当您的设备或设备宽度不是移动/移动尺寸时,您只需将data-src复制到您的src即可。

我相信这是最好的解决方案,因为没有不确定性。通过前面提到的解决方案(我尝试过),您可以使用浏览器与时钟竞争,以便在代码运行时决定加载iframe src。

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

注意:'device'是用于检测移动设备的is-mobile npm包。

© www.soinside.com 2019 - 2024. All rights reserved.