Lazy从iframe API加载youtube视频

时间:2016-06-16 10:25:55

标签: javascript jquery youtube youtube-iframe-api

我想使用iframe API延迟加载youtube视频。即。仅在开头加载海报图像,当用户点击它时,只加载实际图像及其内容。

6 个答案:

答案 0 :(得分:3)

为什么在点击时加载视频,而不仅仅是在用户看到它们时?使用jQuery.Lazy,您无需再做任何事情了。 :)

将插件添加到您的页面:您还需要jQuery或Zepto

<script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazy/1.7.1/jquery.lazy.min.js"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazy/1.7.1/plugins/jquery.lazy.youtube.min.js"></script>

准备您的iFrame:注意data-loaderdata-src属性

<iframe data-loader="youtube" data-src="1AYGnw6MwFM" width="560" height="315"></iframe>

并开始使用Lazy:

$(function() {
    $("iframe[data-src]").Lazy();
});

就是这样!只要用户通过滚动到达iFrame,就会加载iFrame。更多内容here

答案 1 :(得分:2)

大部分内容来自youtube page上的入门部分。

<!-- 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>

此示例在视频准备就绪时加载视频。

因此,我们将其更改为添加到占位符图像中,然后单击隐藏图像并播放视频。

将标签(步骤2)包裹在功能

  function loadYT() {
      var tag = document.createElement('script');
      tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  }

添加图片有关尺寸的详细信息,请查看this question

<div id="placeholder">
    <img src="http://img.youtube.com/vi/M7lc1UVf-VE/sddefault.jpg" />
</div>

然后单击隐藏占位符图像并加载播放器

document.getElementById("placeholder").addEventListener("click", function(){
    this.style.display = 'none';
    loadYT()
});

最终结果如下所示。

<div id="placeholder">
<img src="http://img.youtube.com/vi/M7lc1UVf-VE/sddefault.jpg" />
</div>
</div>
<div id="player"></div>

<script>

document.getElementById("placeholder").addEventListener("click", function(){
    this.style.display = 'none';
    loadYT()
});
  // 2. This code loads the IFrame Player API code asynchronously.
  function loadYT() {
    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>

答案 2 :(得分:1)

may_july <- complete_mc %>% filter( m %in% c(5,7) ) %>% arrange(town, hrvyear, m) # create new column, to check whether the previous month is from the same year and the same town (e.g. we start with may to july comparison) roc <- c() for (i in 1:nrow(may_july)) { if(may_july$hrvyear[i+1] == may_july$hrvyear[i] & may_july$town[i+1] == may_july$town[i]) { roc <- c(roc, TRUE) } else { roc <- c(roc, FALSE) } } # add FALSE for the first row of the roc column, as no previous row exists, # and in order to combine matrix with vector roc <- c(FALSE, roc) tm <- cbind(may_july, roc) # if previous month is from the same year and the same town, calculate the ratio, # if not, add NA roc2 <- c() for(i in 1:nrow(may_july)) { if(roc[i]==TRUE) { roc2 <- c(roc2, (may_july$mean_price[i+1] - may_july$mean_price[i]) / (may_july$mean_price[i])) } else { roc2 <- c(roc2, NA) } } # combine matrix with the final ratios tt <- cbind(may_july, roc2) roc3 <- na.omit(roc2) # calculate the rate of change with the average ratio may_to_july <- (log(1+mean(roc3))/2)*100 mean(roc3) ´´´

此HTML功能允许仅当用户在YouTube <iframe loading="lazy"上滚动时才延迟加载YouTube iframe,而无需任何额外的JavaScript(当然,YouTube视频会通过iframe中的JavaScript自动加载)。< / p>

这是一个工作正常的jsfiddle:https://jsfiddle.net/cirosantilli/3p0tk5nc/1/,我已经在Chromium 81上进行了测试。您可以在开发人员工具的“网络”标签上看到,只有在滚动它们时才加载框架。

由于某些原因,它不适用于Stack Overflow片段,这是因为YouTube视频通常似乎不适用于Stack Overflow,尤其不是因为loading="lazy"

更多详细信息,请访问:lazy load iframe (delay src http call) with jquery

答案 3 :(得分:0)

这个怎么样?

<强> HTML

<div class="wrapper">
    <ul>
        <li><a title="video 1" data-video="http://www.youtube.com/embed/X0DeIqJm4vM">Motherlover</a></li>
        <li><a title="video 2" data-video="http://www.youtube.com/embed/GI6CfKcMhjY">Jack Sparrow</a></li>
        <li><a title="video 3" data-video="http://www.youtube.com/embed/TcK0MYgnHjo">Ras trent</a></li>
        <li><a title="video 4" data-video="http://www.youtube.com/embed/8yvEYKRF5IA">Boombox</a></li>
        <li><a title="video 5" data-video="http://www.youtube.com/embed/6_W_xLWtNa0">Shy Ronnie 2</a></li>
    </ul>
    <iframe id="videoArea" width="350" height="250" src="http://www.youtube.com/embed/X0DeIqJm4vM" frameborder="0" allowfullscreen></iframe>
</div>

<强> JS

var initVideos = function() {
    var videoArea = $("#videoArea"),
        divs = $("ul li a"); // or some other data format

    // bind your hover event to the divs
    divs.click(function(ev) {
        ev.preventDefault();
        videoArea.prop("src", $(this).data('video'));
        divs.removeClass("active");
        $(this).addClass("active");
    });
};

// once the DOM is ready
$(function() {
    initVideos();
});

<强> DEMO

答案 4 :(得分:0)

对我来说这适用于多个视频:

<?php $youtubevideo="Video ID1"; $youtubezaehler=$youtubezaehler+1;?>
<br>
 <div align="center" class="video-container" onmouseover="video<?php echo($youtubezaehler);?>()">
<div style="position:relative;">
<a href="javascript:video<?php echo($youtubezaehler);?>()"><img loading="lazy" id="vorschaubild<?php echo($youtubezaehler);?>" class="" src="https://img.youtube.com/vi/<?php echo($youtubevideo);?>/<?php echo $youtube_aufloesung; ?>" width="100%" alt="Lade..."></a>
<div id="play<?php echo($youtubezaehler);?>" style="position:absolute; top:30%; left:46%; width:10%;"><img src="play.gif" alt="Play" style="width:100%;"></div>
</div>
<script type="text/javascript">
<!--
//JavaScript zum DSGVO konformem und Ladezeitoptimierten Einbinden der Youtube Videos erst bei Nutzung
function video<?php echo($youtubezaehler);?>() {
if(document.getElementById("vorschaubild<?php echo($youtubezaehler);?>").style.visibility=="hidden") return false; //Damit das Video nicht beim abspielen versehntlich neu geladen wird
document.getElementById("vorschaubild<?php echo($youtubezaehler);?>").height = "1px";
document.getElementById("vorschaubild<?php echo($youtubezaehler);?>").style.visibility="hidden";
document.getElementById("play<?php echo($youtubezaehler);?>").style.visibility="hidden";
document.getElementById("video<?php echo($youtubezaehler);?>").src = "https://www.youtube-nocookie.com/embed/<?php echo($youtubevideo);?>?rel=0";
}
// -->
</script>
    <iframe title="Video" id="video<?php echo($youtubezaehler);?>" src="" frameborder="0" allowfullscreen></iframe>
</div>







<?php $youtubevideo="Video ID2"; $youtubezaehler=$youtubezaehler+1;?>
<br>
 <div align="center" class="video-container" onmouseover="video<?php echo($youtubezaehler);?>()">
<div style="position:relative;">
<a href="javascript:video<?php echo($youtubezaehler);?>()"><img loading="lazy" id="vorschaubild<?php echo($youtubezaehler);?>" class="" src="https://img.youtube.com/vi/<?php echo($youtubevideo);?>/<?php echo $youtube_aufloesung; ?>" width="100%" alt="Lade..."></a>
<div id="play<?php echo($youtubezaehler);?>" style="position:absolute; top:30%; left:46%; width:10%;"><img src="play.gif" alt="Play" style="width:100%;"></div>
</div>
<script type="text/javascript">
<!--
//JavaScript zum DSGVO konformem und Ladezeitoptimierten Einbinden der Youtube Videos erst bei Nutzung
function video<?php echo($youtubezaehler);?>() {
if(document.getElementById("vorschaubild<?php echo($youtubezaehler);?>").style.visibility=="hidden") return false; //Damit das Video nicht beim abspielen versehntlich neu geladen wird
document.getElementById("vorschaubild<?php echo($youtubezaehler);?>").height = "1px";
document.getElementById("vorschaubild<?php echo($youtubezaehler);?>").style.visibility="hidden";
document.getElementById("play<?php echo($youtubezaehler);?>").style.visibility="hidden";
document.getElementById("video<?php echo($youtubezaehler);?>").src = "https://www.youtube-nocookie.com/embed/<?php echo($youtubevideo);?>?rel=0";
}
// -->
</script>
    <iframe title="Video" id="video<?php echo($youtubezaehler);?>" src="" frameborder="0" allowfullscreen></iframe>
</div>

答案 5 :(得分:-2)

最后它起作用了,下面的代码是angularJS。

<强> HTML

<div data-ng-repeat="video in videoIds track by $index">
    <div id="uniQueId" ng-click="playVideo(video, 'player' + $index)">
        <div class="video-play-button"></div>
    </div>
</div>

<强> JS

 $scope.playVideo = function(videoId, id) {
        $scope.players[id] = new YT.Player(id, {
            videoId: videoId,
            width: '400',
            height: '300',
            playerVars: { 'autoplay': 1 },
            events: {
                'onStateChange': $scope.onPlayerStateChange
            }
        });
    };
相关问题