简体   繁体   English

设置计时器以等待swfobject脚本加载Flash后备视频播放器

[英]Setting a timer to wait for swfobject script to load for flash fallback video player

Hi there i have built a page that needs to display multiple videos. 嗨,我建立了一个页面,需要显示多个视频。 It tests to see if the videos can be played in the browser (mp4 format) and if so will construct an HTML5 video tag. 它会测试视频是否可以在浏览器中播放(mp4格式),如果可以,将构造一个HTML5视频标签。 If the video can't be played natively in the browser then it will fallback to flash. 如果无法在浏览器中本地播放视频,则它将回退到Flash。 The problem i am having is that if it can't play the Mp4 file i have to load the swfobject.js file to set up the flash player - but i only want to do this once. 我遇到的问题是,如果它不能播放Mp4文件,我必须加载swfobject.js文件来设置Flash Player-但我只想这样做一次。

I am setting a global variable of swfObjLoaded to false and then trying to do an ajax load on the script. 我将swfObjLoaded的全局变量设置为false,然后尝试在脚本上进行ajax加载。 However the swfobject script seems to be loading really slowly so the registration of the swf is trying to occur before the script has fully loaded. 但是swfobject脚本的加载速度似乎非常缓慢,因此swf的注册尝试在脚本完全加载之前进行。 I am therefore trying to use setInterval to repeatedly check to see if swfObjLoaded is set to true and if it is cancel the interval and run the setupFlash function. 因此,我尝试使用setInterval反复检查swfObjLoaded是否设置为true,以及是否取消间隔并运行setupFlash函数。

This is not working at all and seems to be hanging my browser. 这根本不起作用,似乎正在挂起我的浏览器。 Anyone know the best way to go about doing this. 任何人都知道执行此操作的最佳方法。 I know the jQuery deferred function could probably really help me out here, but unfortunately i am stuck with using jQuery 1.3.2 which doesn't contain the deferred function. 我知道jQuery延迟函数可能确实可以在这里为我提供帮助,但是不幸的是,我坚持使用不包含延迟函数的jQuery 1.3.2。 Any ideas? 有任何想法吗?

Here is my code: 这是我的代码:

<html>
    <head>
        <title>HTML5 multiple videos test</title>
        <script type="text/javascript" src="http://media.topshop.com/javascript/3.3.2.3/lib/jquery/jquery.js"></script>
    </head>
    <body>

        <div style="width: 640px; height: 360px;">
            <div style="background-color: #ffe9db; width: 100%; height: 100%;">
                <div class="video_container_1" style="display: block; width: 420px; height: 236px;">
                    <a class="html5_vid" href="http://media.topshop.com/cms/pages/static/static-0000035506/flash/topshop_unique_2012_420x236.mp4">
                        <img src="http://media.topshop.com/wcsstore/ConsumerDirectStorefrontAssetStore/images/colors/color7/cms/pages/static/static-0000035506/images/VIDEO_LEFT.jpg" alt="Download the Nick Knight video" />
                    </a>
                </div>
            </div>
        </div>
        <div style="width: 640px; height: 360px;">
            <div style="background-color: #ffe9db; width: 100%; height: 100%;">
                <div class="video_container_2" style="display: block; width: 407px; height: 224px;">
                    <a class="html5_vid" href="http://www.topshop.com/cms/pages/static/static-0000035506/flash/NEW_MAKEUP-HAIR-NAILS_02_a420X236.mp4">
                        <img src="http://media.topshop.com/wcsstore/ConsumerDirectStorefrontAssetStore/images/colors/color7/cms/pages/static/static-0000035506/images/VIDEO_RIGHT.jpg" alt="Download the Nick Knight video" />
                    </a>
                </div>
            </div>
        </div>

    <script type="text/javascript">

      var vidLink = $("a.html5_vid"),
          canPlay = false,
          v = document.createElement("video"),
          vidCounter = 1,
          swfObjLoaded = false,
          interval,
          flashCode = '<object id="flash_vid_vidCount" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="vidWidth" height="vidHeight"><param name="movie" value="http://media.topshop.com/flash_content/player_page/videoPlayer.swf" \/><param name="allowFullScreen" value="true" \/><param name="allowScriptAccess" value="always" \/><param name="wmode" value="transparent" \/><param name="bgcolor" value="#ffffff" \/><param name="FlashVars" value="source=vidUrl&amp;still=posterUrl" \/><object width="vidWidth" height="vidHeight" type="application/x-shockwave-flash" flashvars="source=vidUrl&amp;still=posterUrl" data="http://media.topshop.com/flash_content/player_page/videoPlayer.swf" allowfullscreen="true" allowscriptaccess="always" wmode="transparent" bgcolor="#ffffff"><a title="Get Flash Player" href="http://www.adobe.com/go/getflashplayer"><img src="posterUrl" border="0" alt="Get Flash Player" width="vidWidth" height="vidHeight" \/><\/a><\/object><\/object>';

      if(v.canPlayType && v.canPlayType("video/mp4").replace(/no/, "")) {
        canPlay = true;
      } else {
        $.ajax({
            url: 'http://media.topshop.com/javascript/behaviour/swfobject.js',
            dataType: "script",
            async: false,
            success: function() {
                console.log("loaded the file via ajax");
                swfObjLoaded = true;
            }
        });
      }

      $.each(vidLink, function() {
        var currentLink = $(this);
        currentLink.css("display", "none");
        var vidUrl = currentLink.attr("href"),
            posterUrl = currentLink.children("img").attr("src"),
            vidContainer = currentLink.parent(),
            vidContainerParent = vidContainer.parent(),
            vidWidth = vidContainer.css("width").replace("px", ""),
            vidHeight = vidContainer.css("height").replace("px", "");

        if (canPlay === true) {
          console.log("canPlay is true");
          newVid = document.createElement("video");
          currentLink.replaceWith(newVid);
          $("div.video_container_" + vidCounter + " video").attr({id: "html_vid_" + vidCounter, controls: "controls", width: vidWidth, height: vidHeight}).append("<source src=" + vidUrl + " \/>");
          if(!$("div.video_container_" + vidCounter + " video").children("source").length) {
            $("div.video_container_" + vidCounter + " video").attr("src", vidUrl );
          }
          if (navigator.userAgent.toLowerCase().search("android") > -1) {
            var vid = document.getElementById("html_vid_" + vidCounter);
            vid.onclick = function() {
              if (vid.paused) {
                vid.play();
              } else {
                vid.pause();
              }
            }
          }
        } else {
          console.log("canPlay is false");
            function setupFlash() {
                vidContainerParent.hide();
                var tempFlashCode = flashCode.replace(/vidCount/g, vidCounter);
                    tempFlashCode = tempFlashCode.replace(/vidWidth/g, vidWidth);
                    tempFlashCode = tempFlashCode.replace(/vidHeight/g, vidHeight);
                    tempFlashCode = tempFlashCode.replace(/vidUrl/g, vidUrl);
                    tempFlashCode = tempFlashCode.replace(/posterUrl/g, posterUrl);
                swfobject.registerObject("flash_vid_" + vidCounter, "9.0.0");
                currentLink.replaceWith(tempFlashCode);
                vidContainerParent.show();
            }

            function checkSwfObj() {
                if (swfObjLoaded !== true) {
                    console.log("still not loaded");
                    var timer = setInterval(function(){checkSwfObj()},100);
                } else {
                    console.log("bloody thing is finally loaded");
                    clearInterval(timer);
                    setupFlash();
                }
            }
            checkSwfObj();
        }
        vidCounter++;
      });
    </script>
    </body>
    </html>

You can define simple loader object like: 您可以定义简单的加载器对象,例如:

var SwfLoader = {
    requestSend: false,
    hasResponse: false,
    callbacks: [],

    bind: function (func) {
        if (this.hasResponse) {
            func();
            return;
        }
        this.callbacks.push(func);
        if (!this.requestSend) this.sendRequest();
    },

    sendRequest: function () {

        this.requestSend = true;

        $.ajax({
            // ....
            // Your request parameters here
            // ....
            success:function () {
                this.hasResponse = true;
                SwfLoader.executeHandlers();
            }
        });
    },

    executeHandlers: function () {
        for (var i = 0; i < this.callbacks.length; i++) {
            this.callbacks[i]();
        }
    }
};

And then use SwfLoader.bind(function () {/* you code to setup flash player */}); 然后使用SwfLoader.bind(function () {/* you code to setup flash player */}); when browser can't play the movie 当浏览器无法播放电影时

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM