如何预加载iframe

NBI*_*NBI 3 javascript iframe preload

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

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

如何在浏览器中摆脱这种加载的可用性?

mon*_*dev 6

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

/sf/answers/3228500761/

在你的情况下,它将是:

<link rel="preload" href="https://example.com/widget.html" as="document">
Run Code Online (Sandbox Code Playgroud)

然后你可以照常使用你的iframe:

<iframe src="https://example.com/widget.html"></iframe>
Run Code Online (Sandbox Code Playgroud)

  • 似乎没有用,似乎这与以下内容有关:https://bugs.chromium.org/p/chromium/issues/detail?id = 593267 (3认同)
  • 这绝对不行。我已经在几个浏览器上尝试过。加载时间不会改变。 (2认同)

Got*_*ttZ 4

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

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

你需要一个..“某种”不可见的容器来预加载 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");
Run Code Online (Sandbox Code Playgroud)

从那里你有很多选择。我建议在原始框架的父元素上使用replaceChild,这样您就可以将它们与预加载的元素交换。
像这样的事情:originalFrame.parentNode.replaceChild(frame, originalFrame);
您还需要重新设置类名等。您也可以使用cloneNode将所有框架属性复制到新框架,
而不是这样做。document.createElement("iframe")