5

Say I want to bind a load-event to an iframe:

var callback = function() {
    //Loaded
};
$('iframe').one('load', callback);

That works well enough, except I can not be sure that the iframe is not already loaded. In that case, the load-event has already fired and my function will never run.

How do I check if the iframe already is loaded?

var callback = function() {
    //Loaded
};
if(iframe already loaded) {
    callback();
} else {
    $('iframe').one('load', callback);
}
Lars Ebert
  • 3,487
  • 2
  • 24
  • 46
  • Check this http://stackoverflow.com/questions/6361465/how-to-check-if-click-event-is-already-bound-jquery – lmgonzalves May 29 '15 at 14:50
  • @lmgonzalves: Thanks, but not quite what I am looking for. I do not want to check for other event-handlers. I want to make sure that the function is run even if I am to late to catch the load event. – Lars Ebert May 29 '15 at 14:52
  • You could check for a method or varibale to be defined in the source of an iframe like [this](http://stackoverflow.com/questions/12173793/access-iframe-functions). If it exists iframe is loaded. – Blauharley May 29 '15 at 14:52
  • @LarsEbert See http://stackoverflow.com/questions/23766086/detect-when-an-iframe-is-loaded/ – guest271314 May 29 '15 at 15:25
  • 1
    See my answer here: http://stackoverflow.com/a/36155560/3894981 – dude Mar 22 '16 at 13:31

1 Answers1

1

You can check readyState:

var iframe = $('iframe');
if (iframe.prop('contentWindow') && iframe.prop('contentWindow').document.readyState === 'complete') {
    callback();
} else {
    iframe.one('load', callback);
}
Blaise
  • 13,139
  • 9
  • 69
  • 97
  • in chrome readystate will be "completed", but using `$iframe.contents().find("*")` will return an empty `body` element. – dude Mar 20 '16 at 19:15