5

I want to catch the load even of any iframe which is appended on the document at some point after loading the page.

I tried using on("load", "iframe", fn), but that doesn't seem to do it:

function addIframe() {
  $("<iframe src='https://example.com'>").appendTo($("body"))
}

// This does not work
$(document).on("load", "iframe", function() {
  alert("loaded, caught via delegation")
})

setTimeout(function() {
  addIframe()
  // This works
  $("iframe").on("load", function() {
    alert("Loaded, caught via direct selection")
  })
}, 1000)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

While $("iframe").on("load", fn), right after appending the iframe works, delegation on the document doesn't work.

How can we detect any iframe load from the page using delegation?

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
  • An iframe is not the same as an img, but the solution described there works in your situation as well. – CertainPerformance Aug 02 '18 at 05:00
  • @CertainPerformance Interesting, [this] works! Thanks! But, how would the jQuery way look in that case? I played [here](http://jsfiddle.net/w27yn1go/6/). – Ionică Bizău Aug 02 '18 at 05:07
  • I googled `jquery usecapture` and found https://stackoverflow.com/questions/24585698/capturing-and-bubbling-using-jquery . Seems impossible with jQuery, have to use `addEventListener`? – CertainPerformance Aug 02 '18 at 05:08
  • @CertainPerformance Yeah... found the same. Anyways, addEventListener seems to work! Thanks! – Ionică Bizău Aug 02 '18 at 05:10

1 Answers1

1

How can we detect any iframe load from the page using delegation?

Unfortunately, It is not possible catching the iframe load events via jQuery delegation.

GhitaB
  • 3,275
  • 3
  • 33
  • 62