Adobe Flex – Loading a SWF at Run-Time

It is typical of a plug-in architecture to load SWFs at run-time.  When I started doing this I realized that SWFs built in Flex look a little different than those built in Flash.

Here is some sample code:

var loader:Loader = new Loader();
var req:URLRequest = new URLRequest(url);
var context:LoaderContext = new LoaderContext();
context.applicationDomain = new ApplicationDomain(ApplicationDomain.currentDomain);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onSwfLoadComplete);
loader.load(req, context);

private function onSwfLoadComplete(e:Event):void {
 var content:DisplayObject = e.target.content;
 var plugIn:IPlugIn;
 // If we don't add it as a child to something, it won't be in the
 // display list and the stage property will be null
 // and Flex will puke, so in this case "plugin_container"
 // is just a mx:UIComponent
 // with it's visible property set to false
 this.plugin_container.addChild(content);

 // If the plug-in was written in Flex, content
 // will be the SystemManager
 // and we need to wait for the Application object
 // to finish loading
 if (content is SystemManager) {
  var sysmgr:SystemManager = (content as SystemManager);
  sysmgr.addEventListener(FlexEvent.APPLICATION_COMPLETE,
   flexPlugInAppComplete);
 }
 else {
  if (content is IPlugIn) {
   plugIn = content as IPlugIn;
   // now you can call a method on your interface such as:
   plugIn.init(this);
  }
 }
}

private function flexPlugInAppComplete(e:FlexEvent):void {
 var sysmgr:SystemManager = (e.currentTarget as SystemManager);
 var swfApp:Application = (sysmgr.application as Application);

 // this is whatever you are using for a plug-in interface
 var plugIn:IPlugIn;

 if (swfApp is IPlugIn) {
  plugIn = swfApp as IPlugIn;
  // now you can call a method on your interface such as:
  plugIn.init(this);
 }
}