I’m changing iframe src using jQuery, I would like it so that while the src content is being loaded, the background of the loading was on top of the iframe itself.

How can I add a style to iframe loading time?

  • Adding style while loading is not a problem. First they added a style, and then they changed the src of the iframe. Do I understand correctly that the main problem is to understand when the document in the iframe is fully loaded and at this moment to remove the loading style? - newman
  • yes that is exactly what is needed - Sdafs Fasafs

2 answers 2

So, we have this code:

 <iframe id="iframe"></iframe> 

Listener to the event is hung before this event can occur (for this reason I did not specify the src attribute).

For example, the code given in one of the answers:

 <div class="iframe-container"> <div class="on-load-iframe-bg"></div> <iframe class="my-iframe" src="you_url"></iframe> </div> $('.my-iframe').on('load', function(){ $(this).closest('.iframe-container').find('.on-load-iframe-bg').remove(); }); 

It can either work or not. A download event may work before you start listening to this event. To avoid such cases, the value of the src attribute is added after the desired listener has been added.

As a result, you need something like this script:

 <script> var iframe = document.querySelector('#iframe'); // Добавляем listener iframe.addEventListener('load', function () { alert('ok'); }); // Загружаем что-то iframe.setAttribute('src', '//###'); </script> 

If you need to catch DOMContentLoaded inside <iframe> , then you should look for something using the iframe contentWindow and iframe contentDocument

  • Well, for that matter, the use of alert is like a bad tone and it is better to replace it with console.log ('ok') - Shnur
  • It does not matter in this context. - nexcode
  • But about the attribute I agree to add it worth it - Shnur
 $('iframe').on('load', function(){ $(this).removeClass('myClassBg'); }); 

Somehow it should work on ideas.

Checked everything works ok. (FireFox & Chrome)

But I would advise doing so.

 .iframe-container {position: relative;} .on-load-iframe-bg {position: absolute;} <div class="iframe-container"> <div class="on-load-iframe-bg"></div> <iframe class="my-iframe"></iframe> </div> 

So it will be more correct:

 (function(){ var $myIframe; $(function(){ $myIframe = $('.my-iframe'); $myIframe.on('load', function(){ $(this).closest('.iframe-container').find('.on-load-iframe-bg').remove(); }); $myIframe.attr('src', 'you_url'); }); })();