问题
Question
Is there a non-polling way for Javascript to command Flash right when its external interface is ready?
Background
In Actionscript, I've registered a function for Javascript to call:
ExternalInterface.addCallback('doStuff", this.doStuff);
I use SWFObject to embed the Flash into my page:
swfobject.embedSWF(
'flash/player.swf',
'flashPlayer',
'100%',
'100%',
'9',
'expressInstallSwfTODO.swf',
{},
{allowfullscreen: true},
{},
function(status) {
if (!status.success) {
alert('Failed to embed Flash player');
} else {
$('flashPlayer').doStuff();
}
}.bind(this)
);
SWFObject lets you run code when Flash has been successfully embedded through a callback. I attempt to run $('flashPlayer').doStuff in this callback, but it claims it's undefined. It seems that Flash needs some time to boot up its external interface. So I've been using a polling hack to find out when the external interface is ready:
new PeriodicalExecutuer(
function(poller) {
if ($('flashPlayer').doStuff) {
$('flashPlayer').doStuff();
poller.stop()
}
},
0.2
);
This poller is not ideal. There's a visually perceptible delay in the execution of doStuff and it makes my overall code structure muddy.
回答1:
In Javascript:
function flashIsReady()
{
$('flashPlayer').doStuff();
}
In Actionscript:
if (ExternalInterface.available) {
ExternalInterface.addCallback('doStuff', this.doStuff);
ExternalInterface.call("flashIsReady");
}
回答2:
I did a polling solution. In actionscript I have a function like this:
private function extIsInterfaceReady():Boolean {
return ExternalInterface.available;
}
And in javascript, after the 'onFlashReady' event I also have coded into intialization, I start an interval like this:
this.poll_flash = setInterval( function() {
if ( typeof this.flash_obj === 'undefined' ) {
return false;
}
if ( typeof this.flash_obj.isInterfaceReady === 'undefined' ) {
return false;
}
if ( this.flash_obj.isInterfaceReady() ) {
clearInterval(this.poll_flash);
return this.continueOn();
}
}, 100);
来源:https://stackoverflow.com/questions/4771379/when-can-javascript-start-calling-actionscript