Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery iframe load() event?

Does anyone know if there is such a thing?

I have a iframe that's being inserted with $.ajax() and I want to do some stuff after the contents from the iframe are completely loaded:

....
 success: function(html){  // <-- html is the IFRAME (#theiframe)
          $(this).html(html);   // $(this) is the container element
          $(this).show();
          $('#theiframe').load(function(){
             alert('loaded!');
          } 
....

it works, but I see the IFRAME is loaded twice (the alert also shows twice).

like image 340
Alex Avatar asked Apr 26 '11 09:04

Alex


People also ask

What is the page load event in jQuery?

The load event occurs when a specified element has been loaded. This event works with elements associated with a URL (image, script, frame, iframe), and the window object. Depending on the browser, the load event may not trigger if the image is cached (Firefox and IE).

Which is the alternative to load event in Ajax?

Use $. ajax instead of . load function. But make sure you specify the dataType as html for the ajax function. .

What is Load event in Javascript?

The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images. This is in contrast to DOMContentLoaded , which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading.


2 Answers

use iframe onload event

$('#theiframe').on("load", function() {
    alert(1);
});
like image 123
m-khonsari Avatar answered Oct 04 '22 23:10

m-khonsari


If possible, you'd be better off handling the load event within the iframe's document and calling out to a function in the containing document. This has the advantage of working in all browsers and only running once.

In the main document:

function iframeLoaded() {
    alert("Iframe loaded!");
}

In the iframe document:

window.onload = function() {
    parent.iframeLoaded();
}
like image 62
Tim Down Avatar answered Oct 05 '22 00:10

Tim Down