我无法让Youtube API在Squarespace中运行

时间:2018-05-31 12:04:49

标签: javascript youtube youtube-api squarespace

我正在尝试在我的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但它不起作用。脚本要注入哪里?

我的代码出了什么问题?

2 个答案:

答案 0 :(得分:0)

根据Youtube IFRAME API,只需在您网址的末尾添加[{name:"toto", id:"emulator-5554"}, {name:"", id:"emulator-5556"}, {name: "toto3", id: "emulator-5558"}] ,例如:

[{name:"toto", id:"emulator-5554"}, {name:"toto4", id:"emulator-5556"}, {name: "toto3", id: "emulator-5558"}]

我认为这也在squarespace forum确认。

答案 1 :(得分: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>