Search code examples
jqueryeventsdomloading

Check if element is loaded


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?


Solution

  • 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() {...}).