user3777369
user3777369

Reputation: 67

Show loading gif every time iframe loads a page

I would like a loading GIF is displayed over an iframe in the parent window whenever a new page is loaded in the iframe. I've seen solutions for questions like this, but they only seem to work for the default page. Once the user navigates away from that page in the iframe, the loading GIF won't show up.

Is this possible using either JavaScript or jQuery? I've tried other solutions on Stack Overflow with no luck.

Upvotes: 1

Views: 3719

Answers (2)

DankMemes
DankMemes

Reputation: 2137

If your frame will always be on the same domain as the parent window, you can register the onbeforeunload event handler on the iframe contentWindow to detect navigating away.

Example:

var iframe = // create or get iframe, make sure no src parameter at first
var unload = function(){
    // show loading gif here
};

var load = function(){
    // hide loading gif here

    iframe.contentWindow.onbeforeunload = unload;
    iframe.onload = load;
};

unload();
iframe.onload = load;
iframe.src = "your url here";

Fiddle: http://jsfiddle.net/qnausxac/1/

Note: Do not register the onbeforeunload event within the iframe using something like

window.onbeforeunload = function(){/* ... */} // BAD

This will overwrite your parent event handler. If you need to detect the event in the iframe then set up some sort of callback with the parent.

Upvotes: 2

Patartics Milán
Patartics Milán

Reputation: 4948

I would start with iframes which have empty src and store the target in another property

<div class="holder">
    <div class="gif-hidden"></div>
    <iframe class="myframe" src="" attr-link="https://google.com/" attr-first="true"></iframe>
</div>

Then when the page loaded successfully, start the animation and set the src values

.gif-hidden should have the display:none or opacity:0 property, while .gif is visible.

$('.gif-hidden').removeClass('gif-hidden').addClass('gif');
$('.myframe').attr('src',$('.myframe').attr('attr-link'));

Also add an event listener to disable the animation once the iframe is loaded at the first time

$('.myframe').load(function(){
     if($(this).attr('attr-first') == "true")
     {
         $(this).attr('attr-first','false');
         $(this).prev().hide();
     }
} 

Didn't tested, but should work.

Upvotes: 0

Related Questions