How do I fire an event when a iframe has finished loading in jQuery?

JavascriptJquery

Javascript Problem Overview


I have to load a PDF within a page.

Ideally I would like to have a loading animated gif which is replaced once the PDF has loaded.

Javascript Solutions


Solution 1 - Javascript

Have you tried:

$("#iFrameId").on("load", function () {
    // do something once the iframe is loaded
});

Solution 2 - Javascript

I'm pretty certain that it cannot be done.

Pretty much anything else than PDF works, even Flash. (Tested on Safari, Firefox 3, IE 7)

Too bad.

Solution 3 - Javascript

This did it for me (not pdf, but another "onload resistant" content):

<iframe id="frameid" src="page.aspx"></iframe>
<script language="javascript">
    iframe = document.getElementById("frameid");

    WaitForIFrame();

    function WaitForIFrame() {
        if (iframe.readyState != "complete") {
            setTimeout("WaitForIFrame();", 200);
        } else {
            done();
        }
    }

    function done() {
        //some code after iframe has been loaded
    }
</script>  

Hope this helps.

Solution 4 - Javascript

I am trying this and seems to be working for me: http://jsfiddle.net/aamir/BXe8C/

Bigger pdf file: http://jsfiddle.net/aamir/BXe8C/1/

Solution 5 - Javascript

$("#iFrameId").ready(function (){
    // do something once the iframe is loaded
});

have you tried .ready instead?

Solution 6 - Javascript

I tried an out of the box approach to this, I havent tested this for PDF content but it did work for normal HTML based content, heres how:

Step 1: Wrap your Iframe in a div wrapper

Step 2: Add a background image to your div wrapper:

.wrapperdiv{
  background-image:url(img/loading.gif);
  background-repeat:no-repeat;
  background-position:center center; /*Can place your loader where ever you like */
}

Step 3: in ur iframe tag add ALLOWTRANSPARENCY="false"

The idea is to show the loading animation in the wrapper div till the iframe loads after it has loaded the iframe would cover the loading animation.

Give it a try.

Solution 7 - Javascript

Using both jquery Load and Ready neither seemed to really match when the iframe was TRULY ready.

I ended up doing something like this

$('#iframe').ready(function () {
    $("#loader").fadeOut(2500, function (sender) {
        $(sender).remove();
    });
});

Where #loader is an absolutely positioned div over top the iframe with a spinner gif.

Solution 8 - Javascript

@Alex aw that's a bummer. What if in your iframe you had an html document that looked like:

<html>
  <head>
    <meta http-equiv="refresh" content="0;url=/pdfs/somepdf.pdf" />
  </head>
  <body>
  </body>
</html>

Definitely a hack, but it might work for Firefox. Although I wonder if the load event would fire too soon in that case.

Solution 9 - Javascript

I had to show a loader while pdf in iFrame is loading so what i come up with:

	loader({href:'loader.gif', onComplete: function(){
			$('#pd').html('<iframe onLoad="loader.close();" src="pdf" width="720px" height="600px" >Please wait... your report is loading..</iframe>');
	}
	});

I'm showing a loader. Once I'm sure that customer can see my loader, i'm calling onCompllet loaders method that loads an iframe. Iframe has an "onLoad" event. Once PDF is loaded it triggers onloat event where i'm hiding the loader :)

The important part:

iFrame has "onLoad" event where you can do what you need (hide loaders etc.)

Solution 10 - Javascript

Here is what I do for any action and it works in Firefox, IE, Opera, and Safari.

<script type="text/javascript">
  $(document).ready(function(){
    doMethod();
  });
  function actionIframe(iframe)
  {
    ... do what ever ...
  }
  function doMethod()
  {   
    var iFrames = document.getElementsByTagName('iframe');
        
    // what ever action you want.
    function iAction()
    {
      // Iterate through all iframes in the page.
      for (var i = 0, j = iFrames.length; i < j; i++)
      {
        actionIframe(iFrames[i]);
      }
    }

    // Check if browser is Safari or Opera.
    if ($.browser.safari || $.browser.opera)
    {
      // Start timer when loaded.
      $('iframe').load(function()
      {
        setTimeout(iAction, 0);
      }
      );

      // Safari and Opera need something to force a load.
      for (var i = 0, j = iFrames.length; i < j; i++)
      {
         var iSource = iFrames[i].src;
         iFrames[i].src = '';
         iFrames[i].src = iSource;
      }
    }
    else
    {
      // For other good browsers.
      $('iframe').load(function()
      {
        actionIframe(this);
      }
      );
    }
  }
</script>

Solution 11 - Javascript

If you can expect the browser's open/save interface to pop up for the user once the download is complete, then you can run this when you start the download:

$( document ).blur( function () {
    // Your code here...
});

When the dialogue pops up on top of the page, the blur event will trigger.

Solution 12 - Javascript

Since after the pdf file is loaded, the iframe document will have a new DOM element <embed/>, so we can do the check like this:

    window.onload = function () {


    //creating an iframe element
    var ifr = document.createElement('iframe');
    document.body.appendChild(ifr);

    // making the iframe fill the viewport
    ifr.width  = '100%';
    ifr.height = window.innerHeight;

    // continuously checking to see if the pdf file has been loaded
     self.interval = setInterval(function () {
        if (ifr && ifr.contentDocument && ifr.contentDocument.readyState === 'complete' && ifr.contentDocument.embeds && ifr.contentDocument.embeds.length > 0) {
            clearInterval(self.interval);
            
            console.log("loaded");
            //You can do print here: ifr.contentWindow.print();
        }
    }, 100); 

    ifr.src = src;
}

Solution 13 - Javascript

The solution I have applied to this situation is to simply place an absolute loading image in the DOM, which will be covered by the iframe layer after the iframe is loaded.

The z-index of the iframe should be (loading's z-index + 1), or just higher.

For example:

.loading-image { position: absolute; z-index: 0; }
.iframe-element { position: relative; z-index: 1; }

Hope this helps if no javaScript solution did. I do think that CSS is best practice for these situations.

Best regards.

Solution 14 - Javascript

function frameLoaded(element) {
    alert('LOADED');
};

 <iframe src="https://google.com" title="W3Schools Free Online Web Tutorials" onload="frameLoaded(this)"></iframe> 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlex AndronovView Question on Stackoverflow
Solution 1 - JavascripttravisView Answer on Stackoverflow
Solution 2 - JavascriptAntti KissaniemiView Answer on Stackoverflow
Solution 3 - JavascriptRon KuperView Answer on Stackoverflow
Solution 4 - JavascriptAamir AfridiView Answer on Stackoverflow
Solution 5 - JavascriptkeithicsView Answer on Stackoverflow
Solution 6 - JavascriptMichael LuView Answer on Stackoverflow
Solution 7 - JavascriptChris MarisicView Answer on Stackoverflow
Solution 8 - JavascripttravisView Answer on Stackoverflow
Solution 9 - JavascriptrinchikView Answer on Stackoverflow
Solution 10 - Javascriptuser22367View Answer on Stackoverflow
Solution 11 - JavascriptEthanView Answer on Stackoverflow
Solution 12 - Javascript令狐葱View Answer on Stackoverflow
Solution 13 - JavascriptElaAleView Answer on Stackoverflow
Solution 14 - JavascriptMahdi BashirpourView Answer on Stackoverflow