等待YouTubePlayerAPI和JQuery文档准备就绪

时间:2015-05-31 23:11:00

标签: jquery youtube-javascript-api document-ready

我的代码中似乎有竞争条件。我通过以下方式异步加载youtube播放器api:

  <script>
    var tag = document.createElement('script');
    tag.src = "https://www.youtube.com/player_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  </script>

使用coffeescript我有:

$ ->
  window.onYouTubePlayerAPIReady = () ->
    #use the youtube player api

有时{J}文档就绪方法会触发onYouTubePlayerAPIReady()方法,在这种情况下,没有任何youtube播放器代码运行。有没有人有任何处理这个的经验或建议?

1 个答案:

答案 0 :(得分:0)

编辑:根据OP(@wuliwong)的反馈(包括示例代码),以下解决方案解决了OP问题中原始暗示的竞争条件:

$(document).bind 'custom-ready', () -> 

    ... custom initialization code ...


# Ensure the 'custom-ready' is called only when both the document and the 
# YouTube player API are ready. As the order this will occur in is not 
# guarenteed the following code caters for both scenarios.

# Cater for the document ready first scenario
$ -> 
    window.onYouTubePlayerAPIReady = () -> 
        $(document).trigger('custom-ready') 

# Cater for YouTube player API ready first scenario
window.onYouTubePlayerAPIReady = () -> 
    $ -> 
        $(document).trigger('custom-ready') 

我的原始答案(上下文):

我过去曾遇到过同样的问题,但设置稍有不同,在我的情况下,我正在加载//www.youtube.com/iframe_api

在这种情况下,我能够将专门依赖于youtube播放器API的代码移到window.onYouTubePlayerAPIReady回调中,然后使用标准<script>包含,例如:

... script tags for non-youtube reliant code ...
<script src="...jquery, plugins, site js..."></script>

... youtube specific code followed by youtube api script tag...
<script>
    window.onYouTubeIframeAPIReady = function () {
        $('.video-gallery').Gallery();
    }
</script>
<script src="//www.youtube.com/iframe_api"></script>

但是,我认为另一种选择是触发就绪状态的自定义事件,例如(在CoffeeScript中)

$(document).bind 'custom-ready', () -> 
    ... code previously in ready event callback ...

$ ->

    # Check if the page includes the youtube player api (this could be
    # achieved in any number of ways, here we assume a CSS class is 
    # applied to the page body as an indicator.
    if $('body.uses-youtube-player-api').length == 0

        # This page doesn't use the youtube player api so call the
        # custom ready event now.
        $(document).trigger('custom-ready')

# If the page does load the youtube player api trigger our custom
# ready event in the associated callback.
window.onYouTubePlayerAPIReady = () ->
    $(document).trigger('custom-ready')

我没有测试过上面的例子,所以这只是一个建议,因为我想我之前解决这个问题的原始例子在很多情况下并不理想。

记住回来我相信这个问题似乎是由浏览器缓存youtube播放器api代码引起的。为了证明这种情况,您可以使用随机字符串加载api播放器(例如,在?_ignore={insert random value}标记script属性前加src前缀)并查看是否可以解决问题,但即使这样做对于用户来说也不是一个有效的解决方案,因为它需要每次访问都重新加载库。