1

I have a button that loads two different pages in two iframes. I need to wait for those loads to complete (like ready(), don't care about images and other content) and then trigger another action. How can I do this?

Jim
  • 485
  • 5
  • 12

3 Answers3

5

One way would be for the iFrame content to signal that it is ready. Here is a simplistic way to do this:

Main Page

var status = [false, false];

function doneLoading(index)
{
   status[index] = true;
   if (status[1] && status[2])
      alert("Both iframes are done loading");
}

In each iFrame

$(document).ready(function() { parent.doneLoading(1) }); // or 2
Nik Kalyani
  • 916
  • 5
  • 10
  • Unfortunately I don't own the pages that are being loaded in the iframes. – Jim Mar 15 '11 at 18:47
  • 2
    You can use the same approach. Just attach an onload event handler to each iframe. $("#iframe1").load(function() { doneLoading(1) }); – Nik Kalyani Mar 15 '11 at 21:24
  • You set [0] and [1] to false, then use [1] and [2]. This is JS so [2] == false anyway. Flawed code and no waiting/callback mechanism. – Lodewijk Sep 14 '14 at 19:02
4

Using $.when() will help you (jQuery 1.5 and higher). For example:

function doAjax(){
   return $.get('foo.htm');
}

function doMoreAjax(){
   return $.get('bar.htm');
}

$.when( doAjax(), doMoreAjax() )
   .then(function(){
      console.log( 'I fire once BOTH ajax requests have completed!' );
   })
   .fail(function(){
      console.log( 'I fire if one or more requests failed.' );
   });
David d C e Freitas
  • 7,481
  • 4
  • 58
  • 67
Dmitry Evseev
  • 11,533
  • 3
  • 34
  • 48
1

In my opinion, the safest solution might be to have a parent iframe that would embedd both iframes and wait for the entire page (the parent page) to load :

$(parent).load(function(){
   ... //if you get there then the 2 iframes are already loaded
}

The drawback is that it's a lot of iframes

Jean-Do
  • 603
  • 5
  • 7