[当前,如果我通过iframe代码将视频放到网站上并使用自动播放模式,那么我在Google Pages Speed Insights上总是会得到很差的分数。我发现只有一种方法可以避免该问题。延迟4秒后才懒于加载视频。但是,所描述的方法不利于用户体验。有人知道更合适的方法来解决此问题吗?
最佳方法是显示图像,然后单击图像时加载视频和所有相关的JS。
下面的方法只是如何执行此操作的示例,在生产环境中,最好使用YouTube API正确地正确加载它,这样,视频就可以点击播放,而不必单击两次,(对于具有声音使用iFrame嵌入),但它应该为您提供一个很好的起点,因为您的问题只是解决问题的方法!
[请注意,由于堆栈溢出的限制,下面的视频将无法播放,这是jsFiddle here that works.,其代码与下面的代码完全相同。
( function() {
var youtube = document.querySelectorAll( ".youtube" );
for (var i = 0; i < youtube.length; i++) {
var source = "https://img.youtube.com/vi/"+ youtube[i].dataset.embed +"/sddefault.jpg";
var image = new Image();
image.src = source;
image.addEventListener( "load", function() {
youtube[ i ].appendChild( image );
}( i ) );
youtube[i].addEventListener( "click", function() {
var iframe = document.createElement( "iframe" );
iframe.setAttribute( "frameborder", "0" );
iframe.setAttribute( "allowfullscreen", "" );
iframe.setAttribute( "src", "https://www.youtube.com/embed/"+ this.dataset.embed +"?rel=0&showinfo=0&autoplay=1" );
this.innerHTML = "";
this.appendChild( iframe );
} );
};
} )();
html {
background-color: #f3f3f3;
}
.wrapper {
max-width: 680px;
margin: 60px auto;
padding: 0 20px;
}
.youtube {
background-color: #000;
margin-bottom: 30px;
position: relative;
padding-top: 56.25%;
overflow: hidden;
cursor: pointer;
}
.youtube img {
width: 100%;
top: -16.82%;
left: 0;
opacity: 0.7;
}
.youtube .play-button {
width: 90px;
height: 60px;
background-color: #333;
box-shadow: 0 0 30px rgba( 0,0,0,0.6 );
z-index: 1;
opacity: 0.8;
border-radius: 6px;
}
.youtube .play-button:before {
content: "";
border-style: solid;
border-width: 15px 0 15px 26.0px;
border-color: transparent transparent transparent #fff;
}
.youtube img,
.youtube .play-button {
cursor: pointer;
}
.youtube img,
.youtube iframe,
.youtube .play-button,
.youtube .play-button:before {
position: absolute;
}
.youtube .play-button,
.youtube .play-button:before {
top: 50%;
left: 50%;
transform: translate3d( -50%, -50%, 0 );
}
.youtube iframe {
height: 100%;
width: 100%;
top: 0;
left: 0;
}
<div class="wrapper">
<div class="youtube" data-embed="U9t-slLl30E">
<div class="play-button"></div>
</div>
</div>