Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind load-event to iframe or run function if the load-event already fired [duplicate]

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);
}
like image 739
Lars Ebert Avatar asked Nov 10 '22 12:11

Lars Ebert


1 Answers

You can check readyState:

var iframe = $('iframe');
if (iframe.prop('contentWindow') && iframe.prop('contentWindow').document.readyState === 'complete') {
    callback();
} else {
    iframe.one('load', callback);
}
like image 101
Blaise Avatar answered Nov 14 '22 22:11

Blaise