P.Henderson
P.Henderson

Reputation: 1091

Waiting for a dynamic iFrame to load using jQuery

Let's say I'm creating a dynamic iFrame like this:

$('body').prepend('<iframe id="e" src="/page.html"></iframe>');

Now I want to wait for this iFrame to finish loading so that I can access its source. I could do this using:

$('#e').load(function() {}

However, if there is an image or anything on "/page.html" that takes a long time to load, then I'm simply waiting for nothing, because all I need is the source.

So my question is, is it possible to do something like this instead:

while not exists ($("#e").contents().find('#someid')) { //wait }

So this simply waits until '#someid' exists in our iFrame (meaning at least the source code finished loaded).

Is this possible?

Upvotes: 0

Views: 820

Answers (1)

Oleg
Oleg

Reputation: 23268

In main window you can declare function (lets say iframeReady):

function iframeReady() {
    //your code
}

And put the following code to the end of body tag inside iframe:

<script>
parent.window.iframeReady();
</script>

So you can access the parent window via parent object

Thus parent.window.iframeReady will be called exactly when body content is loaded and will not wait till all images are loaded

Caveat: it will only work if parent window and iframe have the same domain

Upvotes: 1

Related Questions