我无法让Youtube API在Squarespace中运行

问题描述 投票:0回答:2

我正在尝试在我的squarespace网站中控制youtube iframe。我希望它在页面加载时自动播放,然后如果我滚动并且它不再在视口中,我希望它暂停。

这是我做的:

这是我的iframe:

<iframe id="ytplayer" width="560" height="315" src="https://www.youtube.com/embed/uuRC8Pmud3o?enablejsapi=1&rel=0&showinfo=0&controls=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

这是我的脚本:

<script>
  // 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);

  // This function YouTube player
  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('ytplayer', {
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }  

  // The API will call this function when the video player is ready.
  function onPlayerReady(event) {
    event.target.playVideo();
  }

  // The API calls this function when the player's state changes.
  var done = false;
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING) {
      done = true;
    }
    // Loop the video
    if (event.data == YT.PlayerState.ENDED) {
      player.playVideo(); 
    }
  }

  // On scroll Pause/Play the video player
  $(window).scroll(function() {
    var top_of_element = $("#ytplayer").offset().top;
    var bottom_of_element = $("#ytplayer").offset().top + $("#ytplayer").outerHeight();
    var bottom_of_screen = $(window).scrollTop() + $(window).height();
    var top_of_screen = $(window).scrollTop();

    if((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
      // The element is visible, trigger play click event
      player.playVideo()
    }
    else {
      // The element is not visible, trigger pause click event
      player.pauseVideo()
    }
  });

</script>

我尝试使用多种方法将脚本添加到squarespace但它不起作用。注入脚本在哪里?

我的代码出了什么问题?

javascript youtube youtube-api squarespace
2个回答
0
投票

根据Youtube IFRAME API,只需在网址末尾添加autoplay=1,例如:

<iframe id="ytplayer" type="text/html" width="640" height="360"
  src="https://www.youtube.com/embed/M7lc1UVf-VE?autoplay=1&origin=http://example.com"
  frameborder="0"></iframe>

我认为这也在squarespace forum得到证实。


0
投票

我刚想通了这个。

Squarespace创建了自己的玩家,并且动态创建了iframe,因此它有点复杂。获得使用DOM元素的玩家似乎也不起作用,并且所有iframe元素都具有相同的id =“player”,因此可以解决问题。

下面的代码就是我5分钟前的字面意思。只需复制/粘贴到Squarespace配置中的标头代码注入即可。

它的作用是尽快获取所有原始的YouTube API播放器并暂停播放,以避免在我的旧GPU尝试对所有这些视频实例进行视频解码时出现可怕的延迟。然后我有一个代码,当它出现在屏幕上时播放视频并暂停不再可见的视频。现在它播放顺畅,我可以添加更多视频。在我的情况下,当您向下滚动时,您可以一次看到一个全屏视频。我有7x 720p视频叠加。它看起来很酷,但我发现当使用超过5个视频时我的GPU严重滞后,最初我认为这是一个网络速度问题,但我的任务管理器显示100%的GPU视频编码。到目前为止,在Firefox和Chrome上工作。

我刚刚设法完成这项工作,因此需要进行大量的测试和调整。

使用自己承担风险! :)

<script type="text/javascript">

// Prepare YouTube iframe API ..
// this is probably redundant, but works fine

var tag = document.createElement ('script');

tag.id  = 'iframe-api';
tag.src = 'https://www.youtube.com/iframe_api';

var firstScriptTag = document.getElementsByTagName ('script')[0];

firstScriptTag.parentNode.insertBefore (tag, firstScriptTag);

// When Iframe is ready ..

var iframes = [];
var players = [];

function onYouTubeIframeAPIReady () {

    // console.log ("onYouTubeIframeAPIReady");

    var player_containers = document.querySelectorAll (".sqs-video-background.content-fill");

    for (var i = 0; i < player_containers.length; i ++) {

        player_containers [i].addEventListener ("DOMNodeInserted", function (e) {

            var node = e.target;

            if (node.tagName.toUpperCase () === "IFRAME") {

                // console.log ("PLAYER : " + node.id + " TAG : " + node.tagName);

                iframes.push (node);

                // unfortunately it seems that we cannot catch the player creation event so 
                // the actual players are probably created after this code
                // by calling this function we can catch previous players early on 
                // except the last one

                initPlayers ();
            }

        }, false);
    }
}

function initPlayers () {

    // they have all the same id (!!!)

    // however it seems it picks the last created one so not the same one over and over
    // I didn't touched this, it works so far

    var player = YT.get ("player");

    if (player !== undefined) {

        players.push (player);

        pausePlayer (player);
    }                
}

function playPlayer (player) {

    // this happends when player is not fully initialized yet
    if (typeof player.pauseVideo === "function") {

        player.playVideo ();

    } else {

        // if the player is not ready yet catch the event
        player.addEventListener ('onReady', function (event) { 

            player.playVideo (); 
        });
    }
}

function pausePlayer (player) {

    // this happends when player is not fully initialized yet
    if (typeof player.pauseVideo === "function") {

        player.pauseVideo ();

    } else {

        // if the player is not ready yet catch the event
        player.addEventListener ('onReady', function (event) { 

            player.pauseVideo (); 
        });
    }
}

function isInViewport (element, edge) {

    var h = window.innerHeight;                 // viewport height
    var r = element.getBoundingClientRect ();   // elements bounding rect in viewport coordinates

    // console.log ("top    : " + r.top);
    // console.log ("bottom : " + r.bottom);
    // console.log ("height : " + h);

    // add extra margin to the viewport to ensure that 
    // big enough portion of the object is already visible

    var e = h * Math.min (edge, 0.4); // relative viewport factor, max 40%

    var top     = r.top     - e;
    var bottom  = r.bottom  - e;

    h = h - e*2;

    return (!((top > h) || (bottom < 0)));
}

window.onload = function(e){

    // console.log ("loaded");

    initPlayers (); // to catch the last one !

    // console.log ("players : " + players.length);

    function onScroll () {

        for (var i = 0; i < players.length; i ++) {

            var player      = players [i];                
            var iframe      = player.getIframe ();
            var container   = iframe.parentNode;

            if (isInViewport (container, 0.0)) {

                playPlayer  (player);   } else {
                pausePlayer (player);
            }
        }
    }

    // in the case object is already in the viewport
    onScroll ();

    window.addEventListener ("resize", onScroll);
    window.addEventListener ("scroll", onScroll);
}

</script>
© www.soinside.com 2019 - 2024. All rights reserved.