LazyLoaded YouTube Embed Iframe (JavaScript, HTML, CSS)

by pleinx

HTML

<div class="lazy-loaded-iframe">
      <iframe width="100%" height="100%" data-src="http://www.youtube.com/embed/dP15zlyra3c?autoplay=1" data-cover="http://img.youtube.com/vi/dP15zlyra3c/0.jpg"></iframe>
  </div>  

  <script async>
      const iframeClickEvent = (iframe) => {
      		// You can use same logic for window.onload if you want
          // to load iframes after pageload.
          iframe.src = iframe.getAttribute('data-src');

          iframe.onload = () => {
              iframe.parentElement.querySelector('img').remove();
              iframe.style.display = 'block';
          }
      };

      document.querySelectorAll('.lazy-loaded-iframe').forEach(item => {
          const iframe = item.querySelector('iframe');

          const img = document.createElement('img');
          img.src = iframe.getAttribute('data-cover');
          iframe.parentElement.appendChild(img);

          img.addEventListener('click', iframeClickEvent.bind(null, iframe))
      });
  </script>

CSS

.lazy-loaded-iframe iframe {
  display: none;
}

.lazy-loaded-iframe img {
  height: 100%;
  width: 100%;
}
    
/* 16:9 */
.lazy-loaded-iframe {
    position: relative;
    padding: 0;
    padding-bottom: 56.25%;
    max-height: 480px;

}

.lazy-loaded-iframe > iframe,
.lazy-loaded-iframe > img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}