首页 > 解决方案 > 我想按顺序执行该功能

问题描述

一个.html

var iframe = document.querySelector('#test'); 
// iframe.src = 'B.html'

iframe.onload = window(){
   testFunction();
}

B.html

window.onload = window(){
   console.log('B.html');
}

我想要“console.log('B.html') -> TestFunction();”

但是 TestFunction(); 总是先执行。(B.html onload 不起作用。)帮助我...

标签: javascripthtmljspwebiframe

解决方案


您需要您的 iframe 以某种方式与父窗口通信,以表明它已被加载。看看跨文档消息传递。由于跨域策略,我无法在此处放置工作片段,但如果您拥有自己的 Web 服务器,这样的事情应该可以工作:

<iframe id='myFrame' src='B.html' onLoad='onFrameLoad()'></iframe>

// A.html
function receiveMessage(event) {
  console.log('A.html', event);
}
function onFrameLoad(){
  console.log('B.html');
  window.parent.postMessage('loaded');
}
window.addEventListener('message', receiveMessage, false);

推荐阅读