2011-09-30 42 views
0

我有一個JavaScript腳本,使用SWFobject嵌入一個Flash播放器。當我與等待swfobject.js加載給我一個無限循環

swfobject.embedSWF(..) 

嵌入Flash播放器我得到一個錯誤讀取SWFObject的是不確定的。我相信這是因爲我們的網站爲我的應用程序緩存了javascript,但並沒有緩存swfobject.js文件,所以myApp.js調用了swfobject.embedSWF(..)在swfobject.js之前加載了很久。目前,我不能改變什麼東西被緩存,所以我想出了這個解決辦法:

while(!$(that.mediaPlayer).find('#'+that.playerID)[0]){ 
    console.log(that.playerID+' not defined'); 
    that.embedFlashPlayer(1,1); 
} 

... 

this.embedFlashPlayer = function (width, height){ 
    var that = this; 
    var playerID = that.playerID; 
    var server = document.URL.replace(/^.*\/\//,'').replace(/\..*$/,''); 
    var flashvars = {}; 
    var flashSrc = "/flash/AS3MediaPlayer.swf?server"+server+"&playerID="+playerID; 

    //parameters 
    var params = {}; 
    params.movie = flashSrc; 
    params.quality = "high"; 
    params.play = "true"; 
    params.LOOP = "false"; 
    params.wmode = "transparent"; 

    //attributes 
    var attr = {}; 
    attr.classid = "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"; 
    attr.codebase = "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,16,0"; 
    attr.width = "" + width; 
    attr.height = "" + height; 
    attr.id = playerID; 
    //console.log("embedding flash object with id "+playerID); 

    //command to embed flash object 
    try{ 
      swfobject.embedSWF(flashSrc, "no-flash", width, height,"9.0.0","",flashvars,params); 
    }catch(err){ 
     // I DON'T KNOW WHAT TO DO HERE 
    } 

    return true; 
} 

我的代碼檢查,看是否閃光物體已被寫入。如果沒有,則調用在while循環中重複嵌入this.embedFlashPlayer(),直到找到包含swf的div。麻煩的是,這只是永遠循環。如果swfobject未定義,我可以在try-catch塊中做什麼的任何建議?我90%確定這是因爲我的腳本加載速度更快,並且在庫加載之前運行embedSwfObject命令,但我可能是錯誤的。我的腳本在$(function(){...})命令中運行。任何有關如何解決這個問題的理論,建議和想法,我們將不勝感激。

回答

1

while ...?使用window.setInterval

... 
    var interval = window.setInterval(function(){ 
     //Code to check whether the object is ready or not. 
     if($(that.mediaPlayer).find('#'+that.playerID).length){ 
      clearInterval(interval); 
     } 
    }, 100); //Each 100ms = 10 times a second. 
... 

您正在嘗試使用while輪詢setInterval通常用來代替while,因爲(你可能已經注意到了),while會導致瀏覽器「掛起」。

+0

這個解決方案的問題是,在我調用embedFlashObject之後,我需要在下一行中引用flash對象,並且如果我沒有弄錯,setInterval只會設置函數在它自己的'線程'中運行,並且無論flash對象是否已被嵌入,我的腳本都會進展。我需要一種方法來暫停我的腳本,直到找到flash對象。 – aamiri

+0

我接受了你的建議並使用了設定的時間間隔。當我用它直接代替hte while循環它失敗了,就像我想要的那樣。相反,我所做的就是將調用我的腳本的函數包裝在「$(function(){...}」中,並將其封裝在window.setInterval中,然後按照您的建議操作。 – aamiri