.load does not work if element is already loaded

Asked

Viewed 183 times

0

I have the following problem. am using . load to perform an action after loading an iframe

$(document).ready(function() {
   $('iframe').on('load',function()
   { 
       $('#diviframe').fadeTo(200,1);
   });
});

Everything works great, except if the iframe loads before the code. I came to this conclusion because I tested with iframe with only one word (to load faster) and several texts (to take a little longer to load). someone has some idea how to solve this?

1 answer

1

The problem is that jQuery code is running before iframe completes loading.

To ensure that this jQuery code runs after the iframe is loaded, you need to use $(Document).ready. Example:

$(document).ready(function() {
    $('iframe').on('load',function() { 
        $('#diviframe').fadeTo(200,1);
    });
});

Here’s the note that if you’re using jQuery and there’s no reason for iframe, maybe it’s best to load the content by ajax. Example:

$(document).ready(function() {
    $('iframe').load('http://yoursite.tld/pagina', function() { 
        $('#diviframe').fadeTo(200,1);
    });
});

In addition, it should be noted that

$('iframe').load(...)

and

$('iframe').on('load', ...);

work in the same way. By the way, the . on() is recommended and exists from version 1.7 of jQuery (see http://api.jquery.com/on/)

  • Thanks for the reply, but although I have not specified, the code is already ready. Iframe is required as the goal is to upload without refresh. From the tests I’ve done, I believe it’s the iframe that’s being loaded before the code, because only it doesn’t work when the iframe loads too fast.

  • Ok. So maybe you should do the following: Remove the code from the page that includes the iframe and put $(#diviframe). fadeTo(200,1); within a $(Document). ready in the iframe’s own view (page). So your code only depends on the iframe.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.