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:
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?Is there a way I can get the iFrame
.load
event to wait for the 'half preloaded' image to finish loading before firing?
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.