如何预加载iframe

时间:2015-09-13 08:36:25

标签: javascript iframe preload

我有多个iframe来显示页面中的数据 我想在观看当前视图时预加载接下来的3个iframe。我做的如下:

我将隐藏所有iframe并为其设置来源 当我点击特定视图时,我会显示它,在后台我会加载接下来的3个iframe 在执行此操作时,浏览器选项卡中会显示一些加载,并且它看起来并不好看。

如何在浏览器中摆脱此加载以获得可用性?

2 个答案:

答案 0 :(得分:5)

我在那里回答了类似的问题:

https://stackoverflow.com/a/46121439/1951947

在你的情况下,它将是:

<link rel="preload" href="https://example.com/widget.html" as="document">

然后您可以像往常一样使用iframe:

<iframe src="https://example.com/widget.html"></iframe>

答案 1 :(得分:3)

  1. 您无法摆脱浏览器加载指示。

  2. 为什么不直接使用DOM操作创建iframe元素,如下所示..

  3. 你需要一种......“用于预加载iframe的隐形容器。 您需要将iframe放入文档正文中,否则它们将无法开始加载。

    var container = document.createElement("div");
    
    // this will prevent scrollbars in the container
    container.style.overflow = "hidden";
    
    // this ensures the container is always in the visible area
    // sometimes browser don't load what's out of the viewscope so this would help against that
    container.style.position = "fixed";
    
    // this will turn the container "click through"
    container.style.pointerEvents = "none";
    
    // this will render the div invisible:
    container.style.opacity = 0;
    
    // this will try to put the container behind the <body> element:
    container.style.zIndex = -1;
    
    // this will remove any performance loss when scrolling:
    container.style.willChange = "transform";
    
    document.body.appendChild(container);
    
    var framePreload = function (url) {
        var frame = document.createElement("iframe");
        frame.src = url;
        container.appendChild(frame);
        return frame;
    };
    
    var frame = framePreload("https://www.youtube.com/embed/aqz-KE-bpKQ?autoplay=1");
    
    从那里你有很多选择。我建议在原始帧的父元素上使用replaceChild,这样你就可以将它们与预加载的元素交换 像这样:originalFrame.parentNode.replaceChild(frame, originalFrame);
    你还需要重新设置类名等 好而不是做document.createElement("iframe")你也可以使用cloneNode将所有帧属性复制到新帧。