2017-08-29 194 views
0

有下面的代码iFrame内容的加载和onload事件

<iframe id="myframe" src="..."></iframe> 

<script> 
document.getElementById('myframe').onload = function() { 
    alert('myframe is loaded'); 
}; 
</script> 

我是正确的iframe内容是由一个额外的线程加载所以有可能是一个竞争条件? iframe内容是否可能在脚本中的事件处理程序(在主线程中运行)之前加载,导致alert更新显示?

+1

不,你是不正确的。你为什么认为这种方式有效?你研究过了吗?你在'top'中得到了一个执行JS的线程。加载'iframe'后的父页面加载事件(以及链接的JS文件,CSS,图像等其他内容)。见JS小提琴:https://jsfiddle.net/66xe7j1z/ – nothingisnecessary

+0

可能重复的[确切何时IFRAME onload事件触发?](https://stackoverflow.com/questions/815263/exactly-when-does-an- iframe-onload-event-fire) – nothingisnecessary

+0

那么可以保证脚本始终在iframe加载事件发生之前执行? – Mulligun81

回答

0


 

 
    function iframeDidLoad(){ 
 
     alert("Hello World"); 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<iframe id="myiframe" src="#" onLoad="iframeDidLoad();"></iframe>