加载多个iframe而无需重新加载父页面

时间:2020-04-30 12:23:09

标签: javascript html css iframe

我要在页面上加载多个iframe,我的目标是在父页面完成加载后立即加载这些iframe,但是我不希望在加载iframe时重新加载父页面。我试图做的是在父页面窗口完成加载时添加事件侦听器,然后继续将iframe附加到页面。但是,这导致父页面重新加载。下面是对代码的引用。同样,要添加iframe,也可以从与父页面不同的域中添加。

const iFrameResize = (obj) => { console.log(obj) }
const style = "Bla";
window.onload = function() {
  console.log('hey..........')
  var iframe = document.createElement('iframe')
  iframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms"
  iframe.src = "https://iframe.domain.com"
  iframe.width = "100%"
  iframe.frameBorder = "0"
  iframe.id = "iframe-1"
  iframe.onload = function onloadHandler(e) {
    var iframe = e.target
    var iframeId = '#' + iframe.id
    iFrameResize({
      log: true
    }, iframeId)
    iframe.contentWindow.postMessage(style, "*");
  }
  document.body.appendChild(iframe)
}

1 个答案:

答案 0 :(得分:0)

如果确实是window.onload冒泡,也许可以尝试

const iFrameResize = (obj,sel) => {
  console.log(obj,sel)
  document.querySelector(sel).style.display="block";
}
const style = "Bla";

function onloadHandler(e) {
  const iFrame = e.target;
  console.log(iFrame.src)
  const iframeSelector = '#' + iFrame.id
  iFrameResize({
    log: true
  }, iframeSelector)
  iFrame.contentWindow.postMessage(style, "*");
}

window.addEventListener("load", e => {
  console.log(e.target.location.href)
  const iframe = document.createElement('iframe')
  iframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms"
  iframe.width = "100%"
  iframe.frameBorder = "0"
  iframe.style.display="none";
  iframe.id = "iframe-"+document.querySelectorAll("iframe").length;
  iframe.addEventListener("load", onloadHandler);
  iframe.src = "https://google.com/search?q="+iframe.id
  document.body.appendChild(iframe)
})