Defer iframe loading – like Google Maps

Here’s how to do it!

1. Move your iframe src from src to data-src

<iframe src="" data-src="https://www.youtube.com/embed/JdyDz6quE18"></iframe>

HTMLCOPY

2. Add this script in your javascript file or in a <script> tag at the bottom of your page.

function deferIframe() {
  var iframeElem = document.getElementsByTagName('iframe');
  for ( var i = 0; i < iframeElem.length; i++ ) {
    if(iframeElem[i].getAttribute('data-src')) {
      iframeElem[i].setAttribute('src',iframeElem[i].getAttribute('data-src'));
    } 
  } 
}
window.onload = deferIframe;