本文介绍了捕获 iframe 加载完成事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 iframe 的内容从父页面完全加载时捕获?

Is there a way to capture when the contents of an iframe have fully loaded from the parent page?

推荐答案

元素有一个 load 事件.

您如何收听该事件取决于您,但通常最好的方法是:

<iframe> elements have a load event for that.


How you listen to that event is up to you, but generally the best way is to:

1) 以编程方式创建 iframe

它确保您的 load 侦听器始终被调用,方法是在 iframe 开始加载之前附加它.

It makes sure your load listener is always called by attaching it before the iframe starts loading.

<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 标记中使用的另一种方式.


2) inline javascript, is another way that you can use inside your HTML markup.

<script>
function onMyFrameLoad() {
  alert('myframe is loaded');
};
</script>

<iframe id="myframe" src="..." onload="onMyFrameLoad(this)"></iframe>

3) 您也可以在 元素之后,在 标签内附加事件侦听器,但请记住,在这种情况下,有一个在您添加侦听器时,iframe 已经加载的可能性很小.因此,它可能不会被调用(例如,如果 iframe 非常快,或者来自缓存).


3) You may also attach the event listener after the element, inside a <script> tag, but keep in mind that in this case, there is a slight chance that the iframe is already loaded by the time you get to adding your listener. Therefore it's possible that it will not be called (e.g. if the iframe is very very fast, or coming from cache).

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

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

另请参阅我关于哪些元素也可以触发此类型的其他答案load 事件

这篇关于捕获 iframe 加载完成事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 11:27