Search code examples
javascriptswfobjectinfinite-loopexternalinterface

waiting for swfobject.js to load gives me an infinite loop


I have a javascript script that uses SWFobject to embed a flash player. When i got to embed the flash player with

swfobject.embedSWF(..)

i get an error reading that swfobject is undefined. I believe this is happening because our website caches the javascript for my application but doesn't cache the swfobject.js file, so myApp.js, which calls swfobject.embedSWF(..) loads long before swfobject.js. I currently can't change what's being cached, so i came up with this work around:

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;
}

My code checks to see if the flash object has been written. If it hasn't, it calls embed this.embedFlashPlayer() repeatedly in a while loop until the the div containing the swf can be found. The trouble is that this just loops forever. Any suggestion on what i can do in the try-catch block if swfobject is undefined? I am 90% sure this is because my script loads faster and is running the embedSwfObject command before the library has loaded, but i may be wrong. My script runs in $(function(){...}) command. Any theories, suggestions, ideas as to how i can resolve this would be appreciated.


Solution

  • while ...? Use 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.
    ...
    

    You're trying to use while for polling. setInterval is usually used instead of while, because (as you may have noticed), while causes the browser to "hang".