防止 iframe 在移动设备上加载

Mic*_*mes 0 javascript iframe mobile jquery

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

在移动设备上,我希望不加载 iframe,而是使用指向项目的链接在新选项卡中打开站点。

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

在特定设备或视口大小上,有什么方法可以阻止它们完全加载?

sep*_*ott 6

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>
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

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();
Run Code Online (Sandbox Code Playgroud)

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