等待swfobject.js加载给我一个无限循环
问题描述:
我有一个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(){...})命令中运行。任何有关如何解决这个问题的理论,建议和想法,我们将不胜感激。
答
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
会导致浏览器“挂起”。
这个解决方案的问题是,在我调用embedFlashObject之后,我需要在下一行中引用flash对象,并且如果我没有弄错,setInterval只会设置函数在它自己的'线程'中运行,并且无论flash对象是否已被嵌入,我的脚本都会进展。我需要一种方法来暂停我的脚本,直到找到flash对象。 – aamiri
我接受了你的建议并使用了设定的时间间隔。当我用它直接代替hte while循环它失败了,就像我想要的那样。相反,我所做的就是将调用我的脚本的函数包装在“$(function(){...}”中,并将其封装在window.setInterval中,然后按照您的建议操作。 – aamiri