Bind load to iframe event or run function if load event is already fired

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

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

This works pretty well, but I cannot be sure if the iframe is not loaded yet. In this case, the load event is already triggered and my function will never work.

How to check if iframe is loaded?

var callback = function() {
    //Loaded
};
if(iframe already loaded) {
    callback();
} else {
    $('iframe').one('load', callback);
}
+4
source share
1 answer

You can check readyState:

var iframe = $('iframe');
if (iframe.prop('contentWindow') && iframe.prop('contentWindow').document.readyState === 'complete') {
    callback();
} else {
    iframe.one('load', callback);
}
+1
source

All Articles