EduardET

JS: Lazy Load Youtube Videos

Dec 15th, 2017
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <script>
  2. ( function() {
  3.     setTimeout( function() {
  4.         var youtube = document.querySelectorAll( ".youtube" );
  5.  
  6.         for ( var i = 0; i < youtube.length; i++ ) {
  7.  
  8.             var source = "https://img.youtube.com/vi/" + youtube[ i ].dataset.embed + "/sddefault.jpg";
  9.  
  10.             var image = new Image();
  11.             image.src = source;
  12.             image.addEventListener( "load", function() {
  13.                 youtube[ i ].appendChild( image );
  14.             }( i ) );
  15.  
  16.             youtube[ i ].addEventListener( "click", function() {
  17.  
  18.                 var iframe = document.createElement( "iframe" );
  19.  
  20.                 iframe.setAttribute( "frameborder", "0" );
  21.                 iframe.setAttribute( "allowfullscreen", "" );
  22.                 iframe.setAttribute( "src", "https://www.youtube.com/embed/" + this.dataset.embed + "?rel=0&showinfo=0&autoplay=1" );
  23.  
  24.                 this.innerHTML = "";
  25.                 this.appendChild( iframe );
  26.             } );
  27.         };
  28.     }, 100 );
  29. } )();
  30. </script>
Advertisement
Add Comment
Please, Sign In to add comment