Capture iframe load complete event

<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) create your iframe programatically

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="https://stackoverflow.com/questions/3142837/..."; 
document.body.appendChild(iframe); // add it to wherever you need it in the document
</script>

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="https://stackoverflow.com/questions/3142837/..." onload="onMyFrameLoad(this)"></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="https://stackoverflow.com/questions/3142837/..."></iframe>

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

Also see my other answer about which elements can also fire this type of load event

Leave a Comment