javascript - 无法使用 JavaScript 延迟 Youtube CSS
问题描述
出于性能目的,我正在尝试推迟在我的网站上加载 YouTube CSS 和 JavaScript。但是,使用 Google 的 Page Speed Insights 对我的页面进行扫描表明 YouTube CSS 文件https://www.youtube.com/yts/cssbin/www-player-sprite-mode-vflixBY8E.css
没有被延迟。我还测试了删除 JavaScript 以确保 CSS 文件没有被其他资源请求,但事实并非如此。
这是我正在使用的代码:
在我的 main.js 文件中(这是延迟的)
function init() {
var vidDefer = document.getElementsByClassName('youtube');
for (var i=0; i<vidDefer.length; i++) {
if(vidDefer[i].getAttribute('data-src')) {
vidDefer[i].setAttribute('src',vidDefer[i].getAttribute('data-src'));
}
}
}
window.onload = init;
然后,iframe 看起来像这样:
<iframe class="youtube" id="home-youtube" src="" data-src="https://www.youtube.com/embed/QHfgMrpMOm4" frameborder="0" allowfullscreen></iframe>
提前致谢
解决方案
You could always try using Youtube's javascript API and
https://developers.google.com/youtube/iframe_api_reference
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
</body>
</html>
推荐阅读
- javascript - 如何将数据发送到另一个 NextJS 页面?
- powerbi - 如何在 PowerBI 中计算员工人数
- reactjs - ReactDnd-无法将状态从 useDrag 发送到 useDrop
- flutter - 是否有错误的解决方案:参数类型'Stream
' 不能分配给参数类型 'Stream?' - flutter - 如何在 Flutter 中将小部件设置为按钮
- python - 用其他值替换空值
- python - 使用“自定义用户模型”(Django)条纹“webhook”错误
- javascript - 本机代码方法返回未定义而不是字符串
- dataframe - 计算其值落入 SPARK 中每个 bin 的记录数
- java - 如何从 getter 检查用户输入和字段