5

I have a site and an iFrame in that site, as well as a lot of other content (images and so on).

Now I'm using jQuery's $(document).ready(function() { ... }); to execute code. In that code, I'm trying to manipulate content in the iFrame. However, I have to assure the iFrame is loaded to execute the code.

The iFrame usually loads in exactly the same time when the code is executed, so it sometimes fails and sometimes not.

If I use $('#iframe').load(function(){ });, the event is not always executed, because at that moment I attach that load listener, the iFrame may be already finished with loading, and the load event won't get executed again. If I leave it away, the elements are sometimes not yet there (the code get's executed too early).

So what I want to achieve is something like that:

if iFrame is already loaded
  -- execute code 
else 
  -- $('#iframe').load(function() { /*execute code*/ });

Is there a better way to achieve this without using a dirty timeout? Or if using this approach, is there a function which checks if the element is already loaded or not?

user513951
  • 12,445
  • 7
  • 65
  • 82
Florian Müller
  • 7,448
  • 25
  • 78
  • 120
  • change to `.on('load')` - .load() and .on('load') do very different things – treyBake Jul 24 '17 at 14:12
  • This might help you https://stackoverflow.com/questions/12267010/how-can-i-detect-whether-an-iframe-is-loaded – Shiladitya Jul 24 '17 at 14:13
  • @ThisGuyHasTwoThumbs The documentation on .load() says "This method is a shortcut for .on( "load", handler )" - it's still not executed on already loaded elements – Florian Müller Jul 24 '17 at 14:18
  • @FlorianMüller true but - .load() will load a url resource, can be used to import scripts and load data to a div, .on('load') can be used to run functions on the loading of an element – treyBake Jul 24 '17 at 14:19
  • @Shiladitya thanks for the hint, but I guess that's the same approach like Roamer-1888 answered - setting the src element of the iFrame after loading, which extends loading performance time, – Florian Müller Jul 24 '17 at 14:20

3 Answers3

4

For same domain iframe (as it seems to be your case here):

You can check if iframe has some content and then trigger load event using following logic:

$('#iframe').one('load', function(){
  console.log("Sure load event is called!")
}).each(function(){
  if(this.contentDocument.body.children.length) {
    $(this).trigger('load');
  }
})

For handling cross domain iframe too:

Your best bet i guess and if you don't need to support IE8 is probably to capture load event and set it before you set iframe in DOM, by calling it e.g inside head section:

document.addEventListener(
    'load',
    function(event){
        var elm = event.target;
        if( elm.id === 'iframe'){ // or any other filtering condition
            console.log("Sure iframe is loaded!")
        }
    },
    true // Capture event
);
suther
  • 12,600
  • 4
  • 62
  • 99
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • The first variant is actually a nice approach, but contains a very small risk that the content is loaded inbetween these two statements. However it would surely do the deal. Setting the src element after defining the load handler is the brute way but ensures it works. – Florian Müller Jul 24 '17 at 14:46
  • @FlorianMüller In first, i use `$.fn.one()`, not `$.fn.on()`, in purpose to avoid any problem of `small risk that the content is loaded inbetween these two statements`. So whatever happens, it would be called only once (per matched elements in set, here just one element). – A. Wolff Jul 24 '17 at 14:47
3

Make sure that $('#iframe').load(function(){ }); is executed before the iFrame's src is set.

To achieve this, set the src from javascript, not in HTML.

Also, loading sequence matters here. If your jQuery's overall wrapper is jQuery(window).load(function() {...}), the behaviour will be different from that given by jQuery(function() {...}).

Roamer-1888
  • 19,138
  • 5
  • 33
  • 44
1

The DOM always becomes ready before the page is fully loaded, it is usually not safe to attach a load event listener in code executed during a .ready() handler. For example, scripts can be loaded dynamically long after the page has loaded using methods such as $.getScript(). Although handlers added by .ready() will always be executed in a dynamically loaded script, the window's load event has already occurred and those listeners will never run.

jQuery offers several ways to attach a function that will run when the DOM is ready. All of the following syntaxes are equivalent:

  • $( handler )
  • $( document ).ready( handler )
  • $( "document" ).ready( handler )
  • $( "img" ).ready( handler )
  • $().ready( handler )

load () documentation, read () documentation