Why some AS3 swfs work stand alone but fail to load into other swfs
Most developers who create standalone swfs have some standard instantiation code in their class constructor, something like this:
This works fine when the swf is embedded on a page directly as the “stage” property will be available instantaneously.
When this swf is loaded into another swf however, say like this:
addChild(loader);
loader.load(new URLRequest("http://widget.meebo.com/mcr.swf?id=RQYRkTseLc"));
It generates the infamous and ambiguous: TypeError: Error #1009: Cannot access a property or method of a null object reference.
I’m pretty sure this is because when a swf is loaded into another swf, it’s class constructor is called to create the object before it is even added to it’s parent (the Loader object).
Thus the stage property is undefined, which throws the error, which kills the call stack including what ever else was in the constructor after the stage reference.
I’d kind of consider this a bug in the flash architecture.
The work around to insure your swf is compatible with loading into other swfs:
If the stage references are just the above, you can throw a try/catch around them as they would probably get set by the loader anyways:
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
} catch(er:Error) { };
or just ensure the property is available:
or, if there is setup that absolutely requires the stage reference, put this in your constructor:
if (stage){
onAddedToStage();
} else {
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
}
private function onAddedToStage(evt:Event=null):void {
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
initApp();
}