iFrame .load event not waiting for preloading images to finish

1.8k views Asked by At

I have built a portfolio site which contains an iFrame to display artworks. To display each artwork an html page containing a large image is loaded into the iFrame.

The iFrame is hidden whilst empty (display:none) and is supposed to fade up only when the content is fully loaded.

//pass url of artwork page to iFrame
$("#creativeiframe").attr('src', thisLink.attr('href'));

//fade up iFrame once content loaded
$('#creativeiframe').load(function() {
        $('#creativeiframe').fadeIn(300);
});

I had this working as expected - the iFrame would only load up when the content including the large image that had loaded completely, but slow loading prompted me to try preloading the artwork images so they would start downloading before the user clicked to load them into the iFrame.

function preloadImage(url)
{
    var img=new Image();
    img.src=url;
}

Now I have a problem - sometimes when a user clicks to load an artwork the iFrame will fade up showing a half-loaded image, or worse just showing the html content without the image loaded. I have looked at Chrome Dev Tools Network inspector and this appears to occur when the image in question has started preloading, but not finished.

So my questions are:

  1. Does anyone know why this is happening? Is it because with the preloading there is no network request for the image when the iFrame src is changed, so the .load event doesn't wait for the image to load?

  2. Is there a way I can get the iFrame .load event to wait for the 'half preloaded' image to finish loading before firing?

3

There are 3 answers

0
Steve Brown On BEST ANSWER

I got this to work in the end by running a script in the child HTML document to detect the image load. This then triggers a 'fade function' in the parent document which fades up the containing iFrame.

  <script type='text/javascript'>
    var img = new Image();
    img.onload = function(){
        window.parent.fadeFn();
    }
    <?php echo"img.src='".$fileNameVar."'"?> 
  </script>
7
Sho On

There is also a .load() function in the img tag, which can be used to show whether the image is fully loaded or not.

So I think you can use the .load() function to enable/disable the iframe click.

Or show an waiting indicator, maybe better.

2
Tasos Bitsios On

EDIT: this is incorrect, I was confused The load event is fired when the DOM is fully loaded, but that doesn't include external images.

You should be able to do what you want with the ready() event:

//no reason to run the jQuery selector multiple times
var creativeIframe = $("#creativeiframe"); 

//fade up iFrame once content loaded
creativeIframe.ready(function() {
        creativeIframe.fadeIn(300);
});