Загрузка iframe YouTube по клику
Вместо iframe
<iframe width="640" height="360" src="https://www.youtube.com/embed/<?=$item['youtube_id']?>?autoplay=0" allowfullscreen></iframe>
отображаем div
<div class="youtube" id="<?=$item['youtube_id']?>"></div>
css:
.youtube{ background-position:center; background-repeat:no-repeat; position:relative; display:inline-block; overflow:hidden; transition:all 200ms ease-out; cursor:pointer; height:360px; } .youtube .play{ background:url('../images/youtube-play-btn.png') no-repeat; background-position:0 -50px; -webkit-background-size:100% auto; background-size:100% auto; position:absolute; height:50px; width:69px; transition:none; top:0; left:0; right:0; bottom:0; margin:auto; cursor:pointer; } .youtube:hover .play{ background-position:0 0; }
javascript:
'use strict'; function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()} r(function(){ if(!document.getElementsByClassName){ var getElementsByClassName=function(node, classname){ var a=[]; var re=new RegExp('(^| )'+classname+'( |$)'); var els=node.getElementsByTagName("*"); for(var i=0,j=els.length;i<j;i++) if(re.test(els[i].className))a.push(els[i]); return a; } var videos=getElementsByClassName(document.body,"youtube"); } else{ var videos=document.getElementsByClassName("youtube"); } var nb_videos=videos.length; for (var i=0;i<nb_videos;i++){ videos[i].style.backgroundImage='url(https://i.ytimg.com/vi/'+videos[i].id+'/sddefault.jpg)'; var play=document.createElement("div"); play.setAttribute("class","play"); videos[i].appendChild(play); videos[i].onclick=function(){ var iframe=document.createElement("iframe"); var iframe_url="https://www.youtube.com/embed/"+this.id+"?autoplay=1&autohide=1"; if(this.getAttribute("data-params"))iframe_url+='&'+this.getAttribute("data-params"); iframe.setAttribute("src",iframe_url); iframe.setAttribute("frameborder",'0'); iframe.style.width=this.style.width; iframe.style.height=this.style.height; this.parentNode.replaceChild(iframe,this); } } });
Картинка: youtube-play-btn.zip
На основе: https://sitehere.ru/uskorit-zagruzku-stranic-sajta
Лайк