有没有一种方法可以捕获 iframe 的内容何时从父页面完全加载?
最佳答案
<iframe>
元素有一个 load
事件。
如何收听该事件取决于您,但通常最好的方法是:
1) 以编程方式创建您的 iframe
它确保您的 load
总是在 iframe 开始加载之前通过附加它来调用监听器。
<script>
var iframe = document.createElement('iframe');
iframe.onload = function() { alert('myframe is loaded'); }; // before setting 'src'
iframe.src = '...';
document.body.appendChild(iframe); // add it to wherever you need it in the document
</script>
2) 内联 javascript,是您可以在 HTML 标记中使用的另一种方式。
<script>
function onMyFrameLoad() {
alert('myframe is loaded');
};
</script>
<iframe id="myframe" src="..." onload="onMyFrameLoad(this)"></iframe>
3) 你也可以在一个<script>
中在元素之后 附加事件监听器。标记,但请记住,在这种情况下,在您开始添加监听器时,iframe 可能已经加载完毕。因此它可能不被调用(例如,如果 iframe 非常非常快,或者来自缓存)。
<iframe id="myframe" src="..."></iframe>
<script>
document.getElementById('myframe').onload = function() {
alert('myframe is loaded');
};
</script>
另请参阅我关于 which elements can also fire this type of load
event 的其他回答
关于javascript - 捕获 iframe 加载完成事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3142837/