Delay load of iframe?

Viewed 49375

I know there are some tools and techniques for delaying the load of javascript, but I have an iframe that I would like to delay loading until after the rest of the page has finished downloading and rendering (the iframe is in a hidden that will not be revealed until someone clicks on a particular tab on the page. Is there a way to delay the load of an iframe? Any suggestions would be much appreciated. Thanks!

11 Answers

I don't understand why everyone is confusing JAVASCRIPT with JQUERY, but...

The pure JS solution is below: (basically it waits for the DOM to be built then loads all iframes in your page).

<iframe src="" data-src="YOUR ACTUAL iFRAME URL">
<script type="text/javascript">
      function load_iframes() {
var vidDefer = document.getElementsByTagName('iframe');
for (var i=0; i<vidDefer.length; i++) {
if(vidDefer[i].getAttribute('data-src')) {
vidDefer[i].setAttribute('src',vidDefer[i].getAttribute('data-src'));
} } }
      document.addEventListener("DOMContentLoaded", function(event) {
         load_iframes();
      });
    </script>

Note: Be careful about using the document.load event. Any resource that has a problem or has to spend 1 minute to load will stop your code from executing. This code snippet is tweaked (replaced load by domcontentloaded) from this reference.

You can use the loading attribute to lazy load iframes.

<iframe src="https://example.com"
        loading="lazy"
        width="600"
        height="400"></iframe>
window.setTimeout(function(){   
$("#myframe").attr("src","exp3.html");
$("#myframediv").show("slow");
},4000);

try this, this also works.

You can also apply display:none to the iframe with CSS, then use jQuery's .show like this:

$(document).ready(function(){ 
    $('iframe.class_goes_here').show(); 
});
Related