flash.display

# Loader - AS3

Package | flash.display
Class | public class Loader
Inheritance | Loader DisplayObjectContainer InteractiveObject DisplayObject EventDispatcher Object
Subclasses | AVLoader, FlexLoader

Language Version: | ActionScript 3.0

Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4

The Loader class is used to load SWF files or image (JPG, PNG, or GIF) files. Use the `load()` method to initiate loading. The loaded display object is added as a child of the Loader object.

Use the URLLoader class to load text or binary data.

The Loader class overrides the following methods that it inherits, because a Loader object can only have one child display object—the display object that it loads. Calling the following methods throws an exception: `addChild()`, `addChildAt()`, `removeChild()`, `removeChildAt()`, and `setChildIndex()`. To remove a loaded display object, you must remove the Loader object from its parent DisplayObjectContainer child array.

iOS notes

In AIR applications on iOS, you can only load a SWF file containing ActionScript from the application package. This restriction includes any ActionScript, such as assets with class names exported for ActionScript. For loading any SWF file, you must load the SWF using the same application domain as the parent SWF, as shown in the following example:

Copy

     var loader:Loader = new Loader();
     var url:URLRequest = new URLRequest("swfs/SecondarySwf.swf");
     var loaderContext:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain, null);
     loader.load(url, loaderContext);

In addition, on iOS you can't load a SWF file that contains any ActionScript ByteCode (ABC) then unload it and reload it. If you attempt to do this, the runtime throws error 3764.

Prior to AIR 3.6, only SWF files that do not contain ActionScript bytecode can be loaded, regardless of whether they're loaded from the application package or over a network. As an alternative to using an external SWF file with ActionScript, create a SWC library and link it in to your main SWF.

AIR 3.7 and higher supports loading of externally hosted secondary SWFs. The detailed description about this feature can be found here.

These iOS restrictions restrictions do not apply when an application is running in the iOS Simulator (ipa-test-interpreter-simulator or ipa-debug-interpreter-simulator) or interpreter mode (ipa-test-interpreter or ipa-debug-interpreter.)

Loader security

When you use the Loader class, consider the Flash Player and Adobe AIR security model:

- You can load content from any accessible source.
- Loading is not allowed if the calling SWF file is in a network sandbox and the file to be loaded is local.
- If the loaded content is a SWF file written with ActionScript 3.0, it cannot be cross-scripted by a SWF file in another security sandbox unless that cross-scripting arrangement was approved through a call to the `System.allowDomain()` or the `System.allowInsecureDomain()` method in the loaded content file.
- If the loaded content is an AVM1 SWF file (written using ActionScript 1.0 or 2.0), it cannot be cross-scripted by an AVM2 SWF file (written using ActionScript 3.0). However, you can communicate between the two SWF files by using the LocalConnection class.
- If the loaded content is an image, its data cannot be accessed by a SWF file outside of the security sandbox, unless the domain of that SWF file was included in a URL policy file at the origin domain of the image.
- Movie clips in the local-with-file-system sandbox cannot script movie clips in the local-with-networking sandbox, and the reverse is also prevented.
- You cannot connect to commonly reserved ports. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide.

However, in AIR, content in the `application` security sandbox (content installed with the AIR application) are not restricted by these security limitations.

For more information related to security, see the Flash Player Developer Center Topic: Security.

When loading a SWF file from an untrusted source (such as a domain other than that of the Loader object's root SWF file), you may want to define a mask for the Loader object, to prevent the loaded content (which is a child of the Loader object) from drawing to portions of the Stage outside of that mask, as shown in the following code:

     import flash.display.*;
     import flash.net.URLRequest;
     var rect:Shape = new Shape();
     rect.graphics.beginFill(0xFFFFFF);
     rect.graphics.drawRect(0, 0, 100, 100);
     rect.graphics.endFill();
     addChild(rect);
     var ldr:Loader = new Loader();
     ldr.mask = rect;
     var url:String = "http://www.unknown.example.com/content.swf";
     var urlReq:URLRequest = new URLRequest(url);
     ldr.load(urlReq);
     addChild(ldr);

Copy

Note: App Transport Security is being introduced from Apple in iOS9, which doesn’t allow unsecure connections between App and Web services. Due to this change all the connections which are made to Unsecure web sites via Loader, URLLoader will discontinue and not work due to App Transport Security. Please specify exceptions to the default behaviour by adding keys to Info.plist in your app.

To turn off the feature completely you can add following in your Info.plist and it will work as before.

         <key>NSAppTransportSecurity</key>
                   <dict>
                       <key>NSAllowsArbitraryLoads</key><true/>
                   </dict>

Please specify exceptions to the default behavior by adding keys to InfoAdditions tag of application descriptor of your app.

      <iPhone>
      <InfoAdditions>
                       <![CDATA[
                              <key>NSAppTransportSecurity</key>
                                  <dict>
                                            <key>NSExceptionDomains</key>
                                  <dict>
                                           <key>www.example.com</key>
                                  <dict>
                                         <!--Include to allow subdomains-->
                                         <key>NSIncludesSubdomains</key>
                                         <true/>
                                         <!--Include to allow HTTP requests-->
                                         <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
                                         <true/>
                                          <!--Include to specify minimum TLS version-->
                                          <key>NSTemporaryExceptionMinimumTLSVersion</key>
                                          <string>TLSv1.1</string>
                                  </dict>
                                  </dict>
                                  </dict>
                      ]]>
             </InfoAdditions>
      </iPhone>

View the examples

More examples

Loading an external SWF file
Restricting networking APIs

Learn more

Display programming
Basics of display programming
Core display classes
Loading display content dynamically
Taking advantage of mipmapping

Related API Elements

flash.display.LoaderInfo
flash.net.URLLoader
flash.display.DisplayObject

Public Properties
Hide Inherited Public Properties
Show Inherited Public Properties

| Property | Defined By
--- | --- | ---
|  | accessibilityImplementation : AccessibilityImplementation The current accessibility implementation (AccessibilityImplementation) for this InteractiveObject instance. | InteractiveObject
|  | accessibilityProperties : AccessibilityProperties The current accessibility options for this display object. | DisplayObject
|  | alpha : Number Indicates the alpha transparency value of the object specified. | DisplayObject
|  | blendMode : String A value from the BlendMode class that specifies which blend mode to use. | DisplayObject
|  | blendShader : Shader [write-only] Sets a shader that is used for blending the foreground and background. | DisplayObject
|  | cacheAsBitmap : Boolean If set to true, Flash runtimes cache an internal bitmap representation of the display object. | DisplayObject
|  | cacheAsBitmapMatrix : Matrix If non-null, this Matrix object defines how a display object is rendered when cacheAsBitmap is set to true. | DisplayObject
|  | constructor : Object A reference to the class object or constructor function for a given object instance. | Object
|  | content : DisplayObject [read-only] Contains the root display object of the SWF file or image (JPG, PNG, or GIF) file that was loaded by using the load() or loadBytes() methods. | Loader
|  | contentLoaderInfo : LoaderInfo [read-only] Returns a LoaderInfo object corresponding to the object being loaded. | Loader
|  | contextMenu : NativeMenu Specifies the context menu associated with this object. | InteractiveObject
|  | doubleClickEnabled : Boolean Specifies whether the object receives doubleClick events. | InteractiveObject
|  | filters : Array An indexed array that contains each filter object currently associated with the display object. | DisplayObject
|  | focusRect : Object Specifies whether this object displays a focus rectangle. | InteractiveObject
|  | height : Number Indicates the height of the display object, in pixels. | DisplayObject
|  | loaderInfo : LoaderInfo [read-only] Returns a LoaderInfo object containing information about loading the file to which this display object belongs. | DisplayObject
|  | mask : DisplayObject The calling display object is masked by the specified mask object. | DisplayObject
|  | metaData : Object Obtains the meta data object of the DisplayObject instance if meta data was stored alongside the the instance of this DisplayObject in the SWF file through a PlaceObject4 tag. | DisplayObject
|  | mouseChildren : Boolean Determines whether or not the children of the object are mouse, or user input device, enabled. | DisplayObjectContainer
|  | mouseEnabled : Boolean Specifies whether this object receives mouse, or other user input, messages. | InteractiveObject
|  | mouseX : Number [read-only] Indicates the x coordinate of the mouse or user input device position, in pixels. | DisplayObject
|  | mouseY : Number [read-only] Indicates the y coordinate of the mouse or user input device position, in pixels. | DisplayObject
|  | name : String Indicates the instance name of the DisplayObject. | DisplayObject
|  | needsSoftKeyboard : Boolean Specifies whether a virtual keyboard (an on-screen, software keyboard) should display when this InteractiveObject instance receives focus. | InteractiveObject
|  | numChildren : int [read-only] Returns the number of children of this object. | DisplayObjectContainer
|  | opaqueBackground : Object Specifies whether the display object is opaque with a certain background color. | DisplayObject
|  | parent : DisplayObjectContainer [read-only] Indicates the DisplayObjectContainer object that contains this display object. | DisplayObject
|  | root : DisplayObject [read-only] For a display object in a loaded SWF file, the root property is the top-most display object in the portion of the display list's tree structure represented by that SWF file. | DisplayObject
|  | rotation : Number Indicates the rotation of the DisplayObject instance, in degrees, from its original orientation. | DisplayObject
|  | rotationX : Number Indicates the x-axis rotation of the DisplayObject instance, in degrees, from its original orientation relative to the 3D parent container. | DisplayObject
|  | rotationY : Number Indicates the y-axis rotation of the DisplayObject instance, in degrees, from its original orientation relative to the 3D parent container. | DisplayObject
|  | rotationZ : Number Indicates the z-axis rotation of the DisplayObject instance, in degrees, from its original orientation relative to the 3D parent container. | DisplayObject
|  | scale9Grid : Rectangle The current scaling grid that is in effect. | DisplayObject
|  | scaleX : Number Indicates the horizontal scale (percentage) of the object as applied from the registration point. | DisplayObject
|  | scaleY : Number Indicates the vertical scale (percentage) of an object as applied from the registration point of the object. | DisplayObject
|  | scaleZ : Number Indicates the depth scale (percentage) of an object as applied from the registration point of the object. | DisplayObject
|  | scrollRect : Rectangle The scroll rectangle bounds of the display object. | DisplayObject
|  | softKeyboard : String Controls the appearance of the soft keyboard. | InteractiveObject
|  | softKeyboardInputAreaOfInterest : Rectangle Defines the area that should remain on-screen when a soft keyboard is displayed (not available on iOS). | InteractiveObject
|  | stage : Stage [read-only] The Stage of the display object. | DisplayObject
|  | tabChildren : Boolean Determines whether the children of the object are tab enabled. | DisplayObjectContainer
|  | tabEnabled : Boolean Specifies whether this object is in the tab order. | InteractiveObject
|  | tabIndex : int Specifies the tab ordering of objects in a SWF file. | InteractiveObject
|  | textSnapshot : flash.text:TextSnapshot [read-only] Returns a TextSnapshot object for this DisplayObjectContainer instance. | DisplayObjectContainer
|  | transform : flash.geom:Transform An object with properties pertaining to a display object's matrix, color transform, and pixel bounds. | DisplayObject
|  | uncaughtErrorEvents : UncaughtErrorEvents [read-only] An object that dispatches an uncaughtError event when an unhandled error occurs in the SWF that's loaded by this Loader object. | Loader
|  | visible : Boolean Whether or not the display object is visible. | DisplayObject
|  | width : Number Indicates the width of the display object, in pixels. | DisplayObject
|  | x : Number Indicates the x coordinate of the DisplayObject instance relative to the local coordinates of the parent DisplayObjectContainer. | DisplayObject
|  | y : Number Indicates the y coordinate of the DisplayObject instance relative to the local coordinates of the parent DisplayObjectContainer. | DisplayObject
|  | z : Number Indicates the z coordinate position along the z-axis of the DisplayObject instance relative to the 3D parent container. | DisplayObject

Public Methods
Hide Inherited Public Methods
Show Inherited Public Methods

| Method | Defined By
--- | --- | ---
|  | Loader() Creates a Loader object that you can use to load files, such as SWF, JPEG, GIF, or PNG files. | Loader
|  | addChild(child:DisplayObject):DisplayObject Adds a child DisplayObject instance to this DisplayObjectContainer instance. | DisplayObjectContainer
|  | addChildAt(child:DisplayObject, index:int):DisplayObject Adds a child DisplayObject instance to this DisplayObjectContainer instance. | DisplayObjectContainer
|  | addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void Registers an event listener object with an EventDispatcher object so that the listener receives notification of an event. | EventDispatcher
|  | areInaccessibleObjectsUnderPoint(point:Point):Boolean Indicates whether the security restrictions would cause any display objects to be omitted from the list returned by calling the DisplayObjectContainer.getObjectsUnderPoint() method with the specified point point. | DisplayObjectContainer
|  | close():void Cancels a load() method operation that is currently in progress for the Loader instance. | Loader
|  | contains(child:DisplayObject):Boolean Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. | DisplayObjectContainer
|  | dispatchEvent(event:Event):Boolean Dispatches an event into the event flow. | EventDispatcher
|  | getBounds(targetCoordinateSpace:DisplayObject):Rectangle Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object. | DisplayObject
|  | getChildAt(index:int):DisplayObject Returns the child display object instance that exists at the specified index. | DisplayObjectContainer
|  | getChildByName(name:String):DisplayObject Returns the child display object that exists with the specified name. | DisplayObjectContainer
|  | getChildIndex(child:DisplayObject):int Returns the index position of a child DisplayObject instance. | DisplayObjectContainer
|  | getObjectsUnderPoint(point:Point):Array Returns an array of objects that lie under the specified point and are children (or grandchildren, and so on) of this DisplayObjectContainer instance. | DisplayObjectContainer
|  | getRect(targetCoordinateSpace:DisplayObject):Rectangle Returns a rectangle that defines the boundary of the display object, based on the coordinate system defined by the targetCoordinateSpace parameter, excluding any strokes on shapes. | DisplayObject
|  | globalToLocal(point:Point):Point Converts the point object from the Stage (global) coordinates to the display object's (local) coordinates. | DisplayObject
|  | globalToLocal3D(point:Point):Vector3D Converts a two-dimensional point from the Stage (global) coordinates to a three-dimensional display object's (local) coordinates. | DisplayObject
|  | hasEventListener(type:String):Boolean Checks whether the EventDispatcher object has any listeners registered for a specific type of event. | EventDispatcher
|  | hasOwnProperty(name:String):Boolean Indicates whether an object has a specified property defined. | Object
|  | hitTestObject(obj:DisplayObject):Boolean Evaluates the bounding box of the display object to see if it overlaps or intersects with the bounding box of the obj display object. | DisplayObject
|  | hitTestPoint(x:Number, y:Number, shapeFlag:Boolean = false):Boolean Evaluates the display object to see if it overlaps or intersects with the point specified by the x and y parameters. | DisplayObject
|  | isPrototypeOf(theClass:Object):Boolean Indicates whether an instance of the Object class is in the prototype chain of the object specified as the parameter. | Object
|  | load(request:URLRequest, context:LoaderContext = null):void Loads a SWF, JPEG, progressive JPEG, unanimated GIF, or PNG file into an object that is a child of this Loader object. | Loader
|  | loadBytes(bytes:ByteArray, context:LoaderContext = null):void Loads from binary data stored in a ByteArray object. | Loader
|  | loadFilePromise(promise:IFilePromise, context:LoaderContext = null):void Loads an IFilePromise instance. | Loader
|  | local3DToGlobal(point3d:Vector3D):Point Converts a three-dimensional point of the three-dimensional display object's (local) coordinates to a two-dimensional point in the Stage (global) coordinates. | DisplayObject
|  | localToGlobal(point:Point):Point Converts the point object from the display object's (local) coordinates to the Stage (global) coordinates. | DisplayObject
|  | propertyIsEnumerable(name:String):Boolean Indicates whether the specified property exists and is enumerable. | Object
|  | removeChild(child:DisplayObject):DisplayObject Removes the specified child DisplayObject instance from the child list of the DisplayObjectContainer instance. | DisplayObjectContainer
|  | removeChildAt(index:int):DisplayObject Removes a child DisplayObject from the specified index position in the child list of the DisplayObjectContainer. | DisplayObjectContainer
|  | removeChildren(beginIndex:int = 0, endIndex:int = 0x7fffffff):void Removes all child DisplayObject instances from the child list of the DisplayObjectContainer instance. | DisplayObjectContainer
|  | removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void Removes a listener from the EventDispatcher object. | EventDispatcher
|  | requestSoftKeyboard():Boolean Raises a virtual keyboard. | InteractiveObject
|  | setChildIndex(child:DisplayObject, index:int):void Changes the position of an existing child in the display object container. | DisplayObjectContainer
|  | setPropertyIsEnumerable(name:String, isEnum:Boolean = true):void Sets the availability of a dynamic property for loop operations. | Object
|  | stopAllMovieClips():void Recursively stops the timeline execution of all MovieClips rooted at this object. | DisplayObjectContainer
|  | swapChildren(child1:DisplayObject, child2:DisplayObject):void Swaps the z-order (front-to-back order) of the two specified child objects. | DisplayObjectContainer
|  | swapChildrenAt(index1:int, index2:int):void Swaps the z-order (front-to-back order) of the child objects at the two specified index positions in the child list. | DisplayObjectContainer
|  | toLocaleString():String Returns the string representation of this object, formatted according to locale-specific conventions. | Object
|  | toString():String Returns the string representation of the specified object. | Object
|  | unload():void Removes a child of this Loader object that was loaded by using the load() method. | Loader
|  | unloadAndStop(gc:Boolean = true):void Attempts to unload child SWF file contents and stops the execution of commands from loaded SWF files. | Loader
|  | valueOf():Object Returns the primitive value of the specified object. | Object
|  | willTrigger(type:String):Boolean Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type. | EventDispatcher

Events
Click for more information on events
Hide Inherited Events
Show Inherited Events

| Event | Summary | Defined By
--- | --- | --- | ---
|  | activate | [broadcast event] Dispatched when the Flash Player or AIR application gains operating system focus and becomes active. | EventDispatcher
|  | added | Dispatched when a display object is added to the display list. | DisplayObject
|  | addedToStage | Dispatched when a display object is added to the on stage display list, either directly or through the addition of a sub tree in which the display object is contained. | DisplayObject
|  | clear | Dispatched when the user selects 'Clear' (or 'Delete') from the text context menu. | InteractiveObject
|  | click | Dispatched when a user presses and releases the main button of the user's pointing device over the same InteractiveObject. | InteractiveObject
|  | contextMenu | Dispatched when a user gesture triggers the context menu associated with this interactive object in an AIR application. | InteractiveObject
|  | copy | Dispatched when the user activates the platform-specific accelerator key combination for a copy operation or selects 'Copy' from the text context menu. | InteractiveObject
|  | cut | Dispatched when the user activates the platform-specific accelerator key combination for a cut operation or selects 'Cut' from the text context menu. | InteractiveObject
|  | deactivate | [broadcast event] Dispatched when the Flash Player or AIR application operating loses system focus and is becoming inactive. | EventDispatcher
|  | doubleClick | Dispatched when a user presses and releases the main button of a pointing device twice in rapid succession over the same InteractiveObject when that object's doubleClickEnabled flag is set to true. | InteractiveObject
|  | enterFrame | [broadcast event] Dispatched when the playhead is entering a new frame. | DisplayObject
|  | exitFrame | [broadcast event] Dispatched when the playhead is exiting the current frame. | DisplayObject
|  | focusIn | Dispatched after a display object gains focus. | InteractiveObject
|  | focusOut | Dispatched after a display object loses focus. | InteractiveObject
|  | frameConstructed | [broadcast event] Dispatched after the constructors of frame display objects have run but before frame scripts have run. | DisplayObject
|  | gestureDirectionalTap | Dispatched when the user creates a point of contact along the edge of the touch surface with an InteractiveObject instance, (such as tapping along the edge of the touch surface on Siri Remote for Apple TV) Some devices might also interpret this contact as a combination of several touch events, as well. | InteractiveObject
|  | gestureLongPress | Dispatched when the user presses two points of contact over the same InteractiveObject instance on a touch-enabled device (such as presses and releases two fingers over a display object on a mobile phone or tablet with a touch screen). | InteractiveObject
|  | gesturePan | Dispatched when the user moves a point of contact over the InteractiveObject instance on a touch-enabled device (such as moving a finger from left to right over a display object on a mobile phone or tablet with a touch screen). | InteractiveObject
|  | gestureRotate | Dispatched when the user performs a rotation gesture at a point of contact with an InteractiveObject instance (such as touching two fingers and rotating them over a display object on a mobile phone or tablet with a touch screen). | InteractiveObject
|  | gestureSwipe | Dispatched when the user performs a swipe gesture at a point of contact with an InteractiveObject instance (such as touching three fingers to a screen and then moving them in parallel over a display object on a mobile phone or tablet with a touch screen). | InteractiveObject
|  | gestureTap | Dispatched when the user creates a point of contact with an InteractiveObject instance, then taps on a touch-enabled device (such as placing several fingers over a display object to open a menu and then taps one finger to select a menu item on a mobile phone or tablet with a touch screen). | InteractiveObject
|  | gestureZoom | Dispatched when the user performs a zoom gesture at a point of contact with an InteractiveObject instance (such as touching two fingers to a screen and then quickly spreading the fingers apart over a display object on a mobile phone or tablet with a touch screen). | InteractiveObject
|  | imeStartComposition | This event is dispatched to any client app that supports inline input with an IME | InteractiveObject
|  | keyDown | Dispatched when the user presses a key. | InteractiveObject
|  | keyFocusChange | Dispatched when the user attempts to change focus by using keyboard navigation. | InteractiveObject
|  | keyUp | Dispatched when the user releases a key. | InteractiveObject
|  | middleClick | Dispatched when a user presses and releases the middle button of the user's pointing device over the same InteractiveObject. | InteractiveObject
|  | middleMouseDown | Dispatched when a user presses the middle pointing device button over an InteractiveObject instance. | InteractiveObject
|  | middleMouseUp | Dispatched when a user releases the pointing device button over an InteractiveObject instance. | InteractiveObject
|  | mouseDown | Dispatched when a user presses the pointing device button over an InteractiveObject instance. | InteractiveObject
|  | mouseFocusChange | Dispatched when the user attempts to change focus by using a pointer device. | InteractiveObject
|  | mouseMove | Dispatched when a user moves the pointing device while it is over an InteractiveObject. | InteractiveObject
|  | mouseOut | Dispatched when the user moves a pointing device away from an InteractiveObject instance. | InteractiveObject
|  | mouseOver | Dispatched when the user moves a pointing device over an InteractiveObject instance. | InteractiveObject
|  | mouseUp | Dispatched when a user releases the pointing device button over an InteractiveObject instance. | InteractiveObject
|  | mouseWheel | Dispatched when a mouse wheel is spun over an InteractiveObject instance. | InteractiveObject
|  | nativeDragComplete | Dispatched by the drag initiator InteractiveObject when the user releases the drag gesture. | InteractiveObject
|  | nativeDragDrop | Dispatched by the target InteractiveObject when a dragged object is dropped on it and the drop has been accepted with a call to DragManager.acceptDragDrop(). | InteractiveObject
|  | nativeDragEnter | Dispatched by an InteractiveObject when a drag gesture enters its boundary. | InteractiveObject
|  | nativeDragExit | Dispatched by an InteractiveObject when a drag gesture leaves its boundary. | InteractiveObject
|  | nativeDragOver | Dispatched by an InteractiveObject continually while a drag gesture remains within its boundary. | InteractiveObject
|  | nativeDragStart | Dispatched at the beginning of a drag operation by the InteractiveObject that is specified as the drag initiator in the DragManager.doDrag() call. | InteractiveObject
|  | nativeDragUpdate | Dispatched during a drag operation by the InteractiveObject that is specified as the drag initiator in the DragManager.doDrag() call. | InteractiveObject
|  | paste | Dispatched when the user activates the platform-specific accelerator key combination for a paste operation or selects 'Paste' from the text context menu. | InteractiveObject
|  | proximityBegin | Dispatched when the user lowers an active stylus past the proximity detection threshold of the screen. | InteractiveObject
|  | proximityEnd | Dispatched when the user lifts an active stylus above the proximity detection threshold of the screen. | InteractiveObject
|  | proximityMove | Dispatched when the user moves an active stylus over the screen while remaining within the proximity detection threshold. | InteractiveObject
|  | proximityOut | Dispatched when the user moves an active stylus away from this InteractiveObject while remaining within the proximity detection threshold of the screen. | InteractiveObject
|  | proximityOver | Dispatched when the user moves an active stylus directly above this InteractiveObject while remaining within the proximity detection threshold of the screen. | InteractiveObject
|  | proximityRollOut | Dispatched when the user moves an active stylus away from this InteractiveObject and any of its children while remaining within the proximity detection threshold of the screen. | InteractiveObject
|  | proximityRollOver | Dispatched when the user moves an active stylus over this InteractiveObject from outside the object's tree of descendents in the display list (while remaining within the proximity detection threshold of the screen). | InteractiveObject
|  | releaseOutside | Dispatched when a user releases the button on the pointing device after the user first pressed the button over an InteractiveObject instance and then moved the pointing device off of the InteractiveObject instance. | InteractiveObject
|  | removed | Dispatched when a display object is about to be removed from the display list. | DisplayObject
|  | removedFromStage | Dispatched when a display object is about to be removed from the display list, either directly or through the removal of a sub tree in which the display object is contained. | DisplayObject
|  | render | [broadcast event] Dispatched when the display list is about to be updated and rendered. | DisplayObject
|  | rightClick | Dispatched when a user presses and releases the right button of the user's pointing device over the same InteractiveObject. | InteractiveObject
|  | rightMouseDown | Dispatched when a user presses the pointing device button over an InteractiveObject instance. | InteractiveObject
|  | rightMouseUp | Dispatched when a user releases the pointing device button over an InteractiveObject instance. | InteractiveObject
|  | rollOut | Dispatched when the user moves a pointing device away from an InteractiveObject instance. | InteractiveObject
|  | rollOver | Dispatched when the user moves a pointing device over an InteractiveObject instance. | InteractiveObject
|  | selectAll | Dispatched when the user activates the platform-specific accelerator key combination for a select all operation or selects 'Select All' from the text context menu. | InteractiveObject
|  | softKeyboardActivate | Dispatched immediately after the soft keyboard is raised. | InteractiveObject
|  | softKeyboardActivating | Dispatched immediately before the soft keyboard is raised. | InteractiveObject
|  | softKeyboardDeactivate | Dispatched immediately after the soft keyboard is lowered. | InteractiveObject
|  | tabChildrenChange | Dispatched when the value of the object's tabChildren flag changes. | InteractiveObject
|  | tabEnabledChange | Dispatched when the object's tabEnabled flag changes. | InteractiveObject
|  | tabIndexChange | Dispatched when the value of the object's tabIndex property changes. | InteractiveObject
|  | textInput | Dispatched when a user enters one or more characters of text. | InteractiveObject
|  | touchBegin | Dispatched when the user first contacts a touch-enabled device (such as touches a finger to a mobile phone or tablet with a touch screen). | InteractiveObject
|  | touchEnd | Dispatched when the user removes contact with a touch-enabled device (such as lifts a finger off a mobile phone or tablet with a touch screen). | InteractiveObject
|  | touchMove | Dispatched when the user touches the device, and is continuously dispatched until the point of contact is removed. | InteractiveObject
|  | touchOut | Dispatched when the user moves the point of contact away from InteractiveObject instance on a touch-enabled device (such as drags a finger from one display object to another on a mobile phone or tablet with a touch screen). | InteractiveObject
|  | touchOver | Dispatched when the user moves the point of contact over an InteractiveObject instance on a touch-enabled device (such as drags a finger from a point outside a display object to a point over a display object on a mobile phone or tablet with a touch screen). | InteractiveObject
|  | touchRollOut | Dispatched when the user moves the point of contact away from an InteractiveObject instance on a touch-enabled device (such as drags a finger from over a display object to a point outside the display object on a mobile phone or tablet with a touch screen). | InteractiveObject
|  | touchRollOver | Dispatched when the user moves the point of contact over an InteractiveObject instance on a touch-enabled device (such as drags a finger from a point outside a display object to a point over a display object on a mobile phone or tablet with a touch screen). | InteractiveObject
|  | touchTap | Dispatched when the user lifts the point of contact over the same InteractiveObject instance on which the contact was initiated on a touch-enabled device (such as presses and releases a finger from a single point over a display object on a mobile phone or tablet with a touch screen). | InteractiveObject

Property Detail

### content

property

`content:DisplayObject` [read-only]

Language Version: | ActionScript 3.0

Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4

Contains the root display object of the SWF file or image (JPG, PNG, or GIF) file that was loaded by using the `load()` or `loadBytes()` methods.

Implementation
`public function get content():DisplayObject`
Throws

| `SecurityError` — The loaded SWF file or image file belongs to a security sandbox to which you do not have access. For a loaded SWF file, you can avoid this situation by having the file call the `Security.allowDomain()` method or by having the loading file specify a `loaderContext` parameter with its `securityDomain` property set to `SecurityDomain.currentDomain` when you call the `load()` or `loadBytes()` method.

Related API Elements

flash.display.DisplayObject
flash.display.Loader.load()

### contentLoaderInfo

property

`contentLoaderInfo:LoaderInfo` [read-only]

Language Version: | ActionScript 3.0

Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4

Returns a LoaderInfo object corresponding to the object being loaded. LoaderInfo objects are shared between the Loader object and the loaded content object. The LoaderInfo object supplies loading progress information and statistics about the loaded file.

Events related to the load are dispatched by the LoaderInfo object referenced by the `contentLoaderInfo` property of the Loader object. The `contentLoaderInfo` property is set to a valid LoaderInfo object, even before the content is loaded, so that you can add event listeners to the object prior to the load.

To detect uncaught errors that happen in a loaded SWF, use the `Loader.uncaughtErrorEvents` property, not the `Loader.contentLoaderInfo.uncaughtErrorEvents` property.

Implementation
`public function get contentLoaderInfo():LoaderInfo`

Related API Elements

flash.display.LoaderInfo
Example ( How to use this example )
The following example shows how you can load and position an image in ActionScript 3.0 using the Loader class and the complete event on the Loader object's contentLoaderInfo property. Example provided by ActionScriptExamples.com.
Copy

    var url:String = "http://www.helpexamples.com/flash/images/image2.jpg";
    var urlRequest:URLRequest = new URLRequest(url);
    var loader:Loader = new Loader();
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loader_complete);
    loader.load(urlRequest);
    addChild(loader);

    function loader_complete(evt:Event):void {
        var target_mc:Loader = evt.currentTarget.loader as Loader;
        target_mc.x = (stage.stageWidth - target_mc.width) / 2;
        target_mc.y = (stage.stageHeight - target_mc.height) / 2;
    }

### uncaughtErrorEvents

property

`uncaughtErrorEvents:UncaughtErrorEvents` [read-only]

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 10.1, AIR 2

An object that dispatches an `uncaughtError` event when an unhandled error occurs in the SWF that's loaded by this Loader object. An uncaught error happens when an error is thrown outside of any `try..catch` blocks or when an ErrorEvent object is dispatched with no registered listeners.

Note that a Loader object's `uncaughtErrorEvents` property dispatches events that bubble through it, not events that it dispatches directly. It never dispatches an `uncaughtErrorEvent` in the target phase. It only dispatches the event in the capture and bubbling phases. To detect an uncaught error in the current SWF (the SWF in which the Loader object is defined) use the `LoaderInfo.uncaughtErrorEvents` property instead.

If the content loaded by the Loader object is an AVM1 (ActionScript 2) SWF file, uncaught errors in the AVM1 SWF file do not result in an `uncaughtError` event.

Implementation
`public function get uncaughtErrorEvents():UncaughtErrorEvents`

Related API Elements

UncaughtErrorEvent
LoaderInfo.uncaughtErrorEvents
Example ( How to use this example )
The following example demonstrates the use of an uncaught error event handler to detect uncaught errors in a loaded SWF. The example defines an `uncaughtError` event handler to detect uncaught errors.

In the constructor, the code creates a Loader object and registers a listener for the `uncaughtError` event dispatched by the Loader object's `uncaughtErrorEvents` property.

In the `uncaughtErrorHandler()` method, the code checks the data type of the `error` property and responds accordingly.

Copy

    package
    {
        import flash.display.Loader;
        import flash.display.Sprite;
        import flash.events.ErrorEvent;
        import flash.events.UncaughtErrorEvent;
        import flash.net.URLRequest;

        public class LoaderUncaughtErrorEventExample extends Sprite
        {
            private var ldr:Loader;

            public function LoaderUncaughtErrorEventExample()
            {
                ldr = new Loader();
                ldr.load(new URLRequest("child.swf"));
                ldr.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler);
            }

            private function uncaughtErrorHandler(event:UncaughtErrorEvent):void
            {
                if (event.error is Error)
                {
                    var error:Error = event.error as Error;
                    // do something with the error
                }
                else if (event.error is ErrorEvent)
                {
                    var errorEvent:ErrorEvent = event.error as ErrorEvent;
                    // do something with the error
                }
                else
                {
                    // a non-Error, non-ErrorEvent type was thrown and uncaught
                }
            }
        }
    }

Constructor Detail

### Loader

()
Constructor

`public function Loader()`

Language Version: | ActionScript 3.0

Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4

Creates a Loader object that you can use to load files, such as SWF, JPEG, GIF, or PNG files. Call the `load()` method to load the asset as a child of the Loader instance. You can then add the Loader object to the display list (for instance, by using the `addChild()` method of a DisplayObjectContainer instance). The asset appears on the Stage as it loads.

You can also use a Loader instance "offlist," that is without adding it to a display object container on the display list. In this mode, the Loader instance might be used to load a SWF file that contains additional modules of an application.

To detect when the SWF file is finished loading, you can use the events of the LoaderInfo object associated with the `contentLoaderInfo` property of the Loader object. At that point, the code in the module SWF file can be executed to initialize and start the module. In the offlist mode, a Loader instance might also be used to load a SWF file that contains components or media assets. Again, you can use the LoaderInfo object event notifications to detect when the components are finished loading. At that point, the application can start using the components and media assets in the library of the SWF file by instantiating the ActionScript 3.0 classes that represent those components and assets.

To determine the status of a Loader object, monitor the following events that the LoaderInfo object associated with the `contentLoaderInfo` property of the Loader object:

- The `open` event is dispatched when loading begins.
- The `ioError` or `securityError` event is dispatched if the file cannot be loaded or if an error occured during the load process.
- The `progress` event fires continuously while the file is being loaded.
- The `complete` event is dispatched when a file completes downloading, but before the loaded movie clip's methods and properties are available.
- The `init` event is dispatched after the properties and methods of the loaded SWF file are accessible, so you can begin manipulating the loaded SWF file. This event is dispatched before the `complete` handler. In streaming SWF files, the `init` event can occur significantly earlier than the `complete` event. For most purposes, use the `init` handler.

Notes (iOS only): In AIR applications on iOS, you can only load a SWF file containing ActionScript from the application package. This restriction includes any ActionScript, such as assets with class names exported for ActionScript. For loading any SWF file, you must load the SWF using the same application domain as the parent SWF.

Prior to AIR 3.6, only SWF files that do not contain ActionScript bytecode can be loaded, regardless of whether they're loaded from the application package or over a network. As an alternative to using an external SWF file with ActionScript, create a SWC library and link it in to your main SWF.

These restrictions do not apply when an application is running in the iOS Simulator (ipa-test-interpreter-simulator or ipa-debug-interpreter-simulator) or interpreter mode (ipa-test-interpreter or ipa-debug-interpreter.)

Related API Elements

flash.display.Loader.load()
flash.display.LoaderInfo
Method Detail

### close

()
method

`public function close():void`

Language Version: | ActionScript 3.0

Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4

Cancels a `load()` method operation that is currently in progress for the Loader instance.

Related API Elements

flash.display.Loader.load()

### load

()
method

`public function load(request:URLRequest, context:LoaderContext = null):void`

Language Version: | ActionScript 3.0

Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4

Loads a SWF, JPEG, progressive JPEG, unanimated GIF, or PNG file into an object that is a child of this Loader object. If you load an animated GIF file, only the first frame is displayed. As the Loader object can contain only a single child, issuing a subsequent `load()` request terminates the previous request, if still pending, and commences a new load.

Note: In AIR 1.5 and Flash Player 10, the maximum size for a loaded image is 8,191 pixels in width or height, and the total number of pixels cannot exceed 16,777,215 pixels. (So, if an loaded image is 8,191 pixels wide, it can only be 2,048 pixels high.) In Flash Player 9 and earlier and AIR 1.1 and earlier, the limitation is 2,880 pixels in height and 2,880 pixels in width.

A SWF file or image loaded into a Loader object inherits the position, rotation, and scale properties of the parent display objects of the Loader object.

Use the `unload()` method to remove movies or images loaded with this method, or to cancel a load operation that is in progress.

You can prevent a SWF file from using this method by setting the `allowNetworking` parameter of the the `object` and `embed` tags in the HTML page that contains the SWF content.

iOS notes

In AIR applications on iOS, you can only load a SWF file containing ActionScript from the application package. This restriction includes any ActionScript, such as assets with class names exported for ActionScript. For loading any SWF file, you must load the SWF using the same application domain as the parent SWF, as shown in the following example:

Copy

         var loader:Loader = new Loader();
         var url:URLRequest = new URLRequest("swfs/SecondarySwf.swf");
         var loaderContext:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain, null);
         loader.load(url, loaderContext);

In addition, on iOS you can't load a SWF file that contains any ActionScript ByteCode (ABC) then unload it and reload it. If you attempt to do this, the runtime throws error 3764.

Prior to AIR 3.6, only SWF files that do not contain ActionScript bytecode can be loaded, regardless of whether they're loaded from the application package or over a network. As an alternative to using an external SWF file with ActionScript, create a SWC library and link it in to your main SWF.

These restrictions do not apply when an application is running in the iOS Simulator (ipa-test-interpreter-simulator or ipa-debug-interpreter-simulator) or interpreter mode (ipa-test-interpreter or ipa-debug-interpreter.)

Loader security

When you use this method, consider the Flash Player security model, which is described in the Loader class description.

In Flash Player 10 and later, if you use a multipart Content-Type (for example "multipart/form-data") that contains an upload (indicated by a "filename" parameter in a "content-disposition" header within the POST body), the POST operation is subject to the security rules applied to uploads:

- The POST operation must be performed in response to a user-initiated action, such as a mouse click or key press.
- If the POST operation is cross-domain (the POST target is not on the same server as the SWF file that is sending the POST request), the target server must provide a URL policy file that permits cross-domain access.

Also, for any multipart Content-Type, the syntax must be valid (according to the RFC2046 standard). If the syntax appears to be invalid, the POST operation is subject to the security rules applied to uploads.

For more information related to security, see the Flash Player Developer Center Topic: Security.

Parameters

| `request:URLRequest` — The absolute or relative URL of the SWF, JPEG, GIF, or PNG file to be loaded. A relative path must be relative to the main SWF file. Absolute URLs must include the protocol reference, such as http:// or file:///. Filenames cannot include disk drive specifications.
| `context:LoaderContext` (default = `null`)`` — A LoaderContext object, which has properties that define the following:

- Whether or not to check for the existence of a policy file upon loading the object
- The ApplicationDomain for the loaded object
- The SecurityDomain for the loaded object
- The ImageDecodingPolicy for the loaded image object

If the `context` parameter is not specified or refers to a null object, the loaded content remains in its own security domain.

iOS only: When calling the `load()` method in AIR for iOS, the LoaderContext instance must specify the main application domain (`ApplicationDomain.currentDomain`).

For complete details, see the description of the properties in the LoaderContext class.

Events

| `asyncError:`AsyncErrorEvent`` — Dispatched by the `contentLoaderInfo` object if the `LoaderContext.requestedContentParent` property has been specified and it is not possible to add the loaded content as a child to the specified DisplayObjectContainer. This could happen if the loaded content is a `flash.display.AVM1Movie` or if the `addChild()` call to the requestedContentParent throws an error.
| `complete:`Event`` — Dispatched by the `contentLoaderInfo` object when the file has completed loading. The `complete` event is always dispatched after the `init` event.
| `httpStatus:`HTTPStatusEvent`` — Dispatched by the `contentLoaderInfo` object when a network request is made over HTTP and Flash Player can detect the HTTP status code.
| `init:`Event`` — Dispatched by the `contentLoaderInfo` object when the properties and methods of the loaded SWF file are accessible. The `init` event always precedes the `complete` event.
| `ioError:`IOErrorEvent`` — Dispatched by the `contentLoaderInfo` object when an input or output error occurs that causes a load operation to fail.
| `open:`Event`` — Dispatched by the `contentLoaderInfo` object when the loading operation starts.
| `progress:`ProgressEvent`` — Dispatched by the `contentLoaderInfo` object as data is received while load operation progresses.
| `securityError:`SecurityErrorEvent`` — Dispatched by the `contentLoaderInfo` object if a SWF file in the local-with-filesystem sandbox attempts to load content in the local-with-networking sandbox, or vice versa.
| `securityError:`SecurityErrorEvent`` — Dispatched by the `contentLoaderInfo` object if the `LoaderContext.requestedContentParent` property has been specified and the security sandbox of the `LoaderContext.requestedContentParent` does not have access to the loaded SWF.
| `unload:`Event`` — Dispatched by the `contentLoaderInfo` object when a loaded object is removed.

Throws

| `IOError` — The `digest` property of the `request` object is not `null`. You should only set the `digest` property of a URLRequest object when calling the `URLLoader.load()` method when loading a SWZ file (an Adobe platform component).
| `SecurityError` — The value of `LoaderContext.securityDomain` must be either `null` or `SecurityDomain.currentDomain`. This reflects the fact that you can only place the loaded media in its natural security sandbox or your own (the latter requires a policy file).
| `SecurityError` — Local SWF files may not set `LoaderContext.securityDomain` to anything other than `null`. It is not permitted to import non-local media into a local sandbox, or to place other local media in anything other than its natural sandbox.
| `SecurityError` — You cannot connect to commonly reserved ports. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide.
| `SecurityError` — If the `applicationDomain` or `securityDomain` properties of the `context` parameter are from a disallowed domain.
| `SecurityError` — If a local SWF file is attempting to use the `securityDomain` property of the `context` parameter.
| `IllegalOperationError` — If the `requestedContentParent` property of the `context` parameter is a `Loader`.
| `IllegalOperationError` — If the `LoaderContext.parameters` parameter is set to non-null and has some values which are not Strings.
| `IllegalOperationError` — On iOS, if the application attempts to load a SWF file in an application domain other than the main application domain.
| `IllegalOperationError` — On iOS, if the application attempts to reload a SWF that has been loaded and unloaded and the SWF contains ABC code.
| `Error` — On iOS, if the application attempts to load a SWF file from outside the application package that contains ActionScript code. This error can't be caught. It appears as a dialog box on the app screen with the title "Uncompiled ActionScript." Prior to AIR 3.6, this error occurs when you attempt to load any SWF file containing ActionScript, whether it is external or included in the application package.

More examples

Loading display content dynamically

Learn more

Specifying loading context

Related API Elements

contentLoaderInfo
flash.net.URLRequest
flash.display.DisplayObject
flash.display.Loader.unload()
flash.display.LoaderInfo
flash.system.LoaderContext

### loadBytes

()
method

`public function loadBytes(bytes:ByteArray, context:LoaderContext = null):void`

Language Version: | ActionScript 3.0

Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4

Loads from binary data stored in a ByteArray object.

The `loadBytes()` method is asynchronous. You must wait for the "init" event before accessing the properties of a loaded object.

When you use this method, consider the Flash Player security model, which is described in the Loader class description.

Note (iOS only): In AIR applications on iOS, you can only load a SWF file containing ActionScript from the application package. This restriction includes any ActionScript, such as assets with class names exported for ActionScript. For loading any SWF file, you must load the SWF using the same application domain as the parent SWF.

Prior to AIR 3.6, calling this method has no effect on iOS.

Parameters

| `bytes:ByteArray` — A ByteArray object. The contents of the ByteArray can be any of the file formats supported by the Loader class: SWF, GIF, JPEG, or PNG.
| `context:LoaderContext` (default = `null`)`` — A LoaderContext object. Only the `applicationDomain` property of the LoaderContext object applies; the `checkPolicyFile` and `securityDomain` properties of the LoaderContext object do not apply. If the `context` parameter is not specified or refers to a null object, the content is loaded into the current security domain— a process referred to as "import loading" in Flash Player security documentation. Specifically, if the loading SWF file trusts the remote SWF by incorporating the remote SWF into its code, then the loading SWF can import it directly into its own security domain.

For more information related to security, see the Flash Player Developer Center Topic: Security.

Events

| `asyncError:`AsyncErrorEvent`` — Dispatched by the `contentLoaderInfo` object if the `LoaderContext.requestedContentParent` property has been specified and it is not possible to add the loaded content as a child to the specified DisplayObjectContainer. This could happen if the loaded content is a `flash.display.AVM1Movie` or if the `addChild()` call to the requestedContentParent throws an error.
| `complete:`Event`` — Dispatched by the `contentLoaderInfo` object when the operation is complete. The `complete` event is always dispatched after the `init` event.
| `init:`Event`` — Dispatched by the `contentLoaderInfo` object when the properties and methods of the loaded data are accessible. The `init` event always precedes the `complete` event.
| `ioError:`IOErrorEvent`` — Dispatched by the `contentLoaderInfo` object when the runtime cannot parse the data in the byte array.
| `open:`Event`` — Dispatched by the `contentLoaderInfo` object when the operation starts.
| `progress:`ProgressEvent`` — Dispatched by the `contentLoaderInfo` object as data is transfered in memory.
| `securityError:`SecurityErrorEvent`` — Dispatched by the `contentLoaderInfo` object if the `LoaderContext.requestedContentParent` property has been specified and the security sandbox of the `LoaderContext.requestedContentParent` does not have access to the loaded SWF.
| `unload:`Event`` — Dispatched by the `contentLoaderInfo` object when a loaded object is removed.

Throws

| `ArgumentError` — If the `length` property of the ByteArray object is not greater than 0.
| `IllegalOperationError` — If the `checkPolicyFile` or `securityDomain` property of the `context` parameter are non-null.
| `IllegalOperationError` — If the `requestedContentParent` property of the `context` parameter is a `Loader`.
| `IllegalOperationError` — If the `LoaderContext.parameters` parameter is set to non-null and has some values which are not Strings.
| `IllegalOperationError` — On iOS, if the application attempts to load a SWF file in an application domain other than the main application domain.
| `IllegalOperationError` — On iOS, if the application attempts to reload a SWF that has been loaded and unloaded and that contains ABC code.
| `Error` — On iOS, if the application attempts to load a SWF file from outside the application package that contains ActionScript code. This error can't be caught. It appears as a dialog box on the app screen with the message "Uncompiled ActionScript." Prior to AIR 3.6, this error occurs when you attempt to load any SWF file containing ActionScript, whether it is external or included in the application package.
| `SecurityError` — If the provided `applicationDomain` property of the `context` property is from a disallowed domain.
| `SecurityError` — You cannot connect to commonly reserved ports. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide.

Learn more

Loading display content dynamically

Related API Elements

flash.utils.ByteArray
flash.system.LoaderContext.applicationDomain

### loadFilePromise

()
method

`public function loadFilePromise(promise:IFilePromise, context:LoaderContext = null):void`

Language Version: | ActionScript 3.0

Runtime Versions: | AIR 2.5

Loads an IFilePromise instance.

The `loadFilePromise` method takes an `IFilePromise` object and loads the binary data. If the data is a progressive stream, such as a video wait for the "init" or progress events before accessing the properties of the loaded object. Otherwise, wait for the complete event to make sure that the data is fully loaded.

When you use this method, consider the Flash Player security model, which is described in the Loader class description.

Parameters

| `promise:IFilePromise` — An IFilePromise object. The data source of the object can be any of the file formats supported by the Loader class: SWF, GIF, JPEG, or PNG.
| `context:LoaderContext` (default = `null`)`` — A LoaderContext object. Only the `applicationDomain` property of the LoaderContext object applies; the `checkPolicyFile` and `securityDomain` properties of the LoaderContext object do not apply. If the `context` parameter is not specified or refers to a null object, the content is loaded into the current security domain— a process referred to as "import loading" in Flash Player security documentation. Specifically, if the loading SWF file trusts the remote SWF by incorporating the remote SWF into its code, then the loading SWF can import it directly into its own security domain.

For more information related to security, see the Flash Player Developer Center Topic: Security.

Events

| `asyncError:`AsyncErrorEvent`` — Dispatched by the `contentLoaderInfo` object if the `LoaderContext.requestedContentParent` property has been specified and it is not possible to add the loaded content as a child to the specified DisplayObjectContainer. This could happen if the loaded content is a `flash.display.AVM1Movie` or if the `addChild()` call to the requestedContentParent throws an error.
| `complete:`Event`` — Dispatched by the `contentLoaderInfo` object when the operation is complete. The `complete` event is always dispatched after the `init` event.
| `init:`Event`` — Dispatched by the `contentLoaderInfo` object when the properties and methods of the loaded data are accessible. The `init` event always precedes the `complete` event.
| `ioError:`IOErrorEvent`` — Dispatched by the `contentLoaderInfo` object when the runtime cannot parse the data in the data source or if the data source stream is not readable.
| `open:`Event`` — Dispatched by the `contentLoaderInfo` object when the operation starts.
| `progress:`ProgressEvent`` — Dispatched by the `contentLoaderInfo` object as data is transfered in memory.
| `securityError:`SecurityErrorEvent`` — Dispatched by the `contentLoaderInfo` object if the `LoaderContext.requestedContentParent` property has been specified and the security sandbox of the `LoaderContext.requestedContentParent` does not have access to the loaded SWF.
| `unload:`Event`` — Dispatched by the `contentLoaderInfo` object when a loaded object is removed.

Throws

| `IllegalOperationError` — If the `requestedContentParent` property of the `context` parameter is a `Loader`.
| `IllegalOperationError` — If the `LoaderContext.parameters` parameter is set to non-null and has some values which are not Strings.
| `ArgumentError` — If the `IFilePromise` object passed as parameter is null

Related API Elements

MediaPromise
CameraRoll.browseForImage()
CameraUI

### unload

()
method

`public function unload():void`

Language Version: | ActionScript 3.0

Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4

Removes a child of this Loader object that was loaded by using the `load()` method. The `property` of the associated LoaderInfo object is reset to `null`. The child is not necessarily destroyed because other objects might have references to it; however, it is no longer a child of the Loader object.

When you call the `unload()` method, the Loader object's `contentLoaderInfo` property is set to `null`. Any visual assets that were loaded with the SWF are unloaded and removed from memory. ActionScript class definitions in the loaded SWF remain in memory, and code in the same application domain as the loaded SWF can access instances of those classes and create new instances.

Note (iOS only): Prior to AIR 3.6, this method has no effect on iOS.

As a best practice, before you unload a child SWF file, you should explicitly close any streams in the child SWF file's objects, such as LocalConnection, NetConnection, NetStream, and Sound objects. Otherwise, audio in the child SWF file might continue to play, even though the child SWF file was unloaded. To close streams in the child SWF file, add an event listener to the child that listens for the `unload` event. When the parent calls `Loader.unload()`, the `unload` event is dispatched to the child. The following code shows how you might do this:

    function closeAllStreams(evt:Event) {
        myNetStream.close();
        mySound.close();
        myNetConnection.close();
        myLocalConnection.close();
    }

    myMovieClip.loaderInfo.addEventListener(Event.UNLOAD, closeAllStreams);

Related API Elements

Loader.load()
flash.media.Sound.close()
flash.net.LocalConnection.close()
flash.net.NetConnection.close()
flash.net.NetStream.close()
delete operator

### unloadAndStop

()
method

`public function unloadAndStop(gc:Boolean = true):void`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 10, AIR 1.5, Flash Lite 4

Attempts to unload child SWF file contents and stops the execution of commands from loaded SWF files. This method attempts to unload SWF files that were loaded using `Loader.load()` or `Loader.loadBytes()` by removing references to EventDispatcher, NetConnection, Timer, Sound, or Video objects of the child SWF file. As a result, the following occurs for the child SWF file and the child SWF file's display list:

- Sounds are stopped.
- Stage event listeners are removed.
- Event listeners for `enterFrame`, `frameConstructed`, `exitFrame`, `activate` and `deactivate` are removed.
- Timers are stopped.
- Camera and Microphone instances are detached
- Movie clips are stopped.

When you call the `unloadAndStop()` method, the Loader object's `contentLoaderInfo` property is set to `null`. Any visual assets that were loaded with the SWF are unloaded and removed from memory. ActionScript class definitions in the loaded SWF remain in memory, and code in the same application domain as the loaded SWF can access instances of those classes and create new instances.

Note (iOS only): Prior to AIR 3.6, this method has no effect on iOS.

Parameters

| `gc:Boolean` (default = `true`)`` — Provides a hint to the garbage collector to run on the child SWF objects (`true`) or not (`false`). If you are unloading many objects asynchronously, setting the `gc` paramter to `false` might improve application performance. However, if the parameter is set to `false`, media and display objects of the child SWF file might persist in memory after running the `unloadAndStop()` command.

Related API Elements

flash.display.DisplayObject
flash.display.Loader.load()
Examples How to use this example
LoaderExample.as
The following example uses the LoaderExample class to illustrate how various event listeners are used. This task is accomplished by performing the following steps:

1. A `url` property is created, which is the location and name of the image file
2. In the `LoaderExample` constructor, a new Loader object named `loader` is created, which is then passed to the `configureListeners()` method, described in step 3.
3. The constructor creates a new instance of a URLRequest object, `request`, with `url` passed so that the file name and location are known.
4. The `request` object is passed to the `loader` object's `load()` method, which loads the image onto the display list.
5. A `clickHandler` event listener is registered for the `click` event on the loader. After a mouse click, the loaded image is unloaded.
6. The `configureListeners()` method adds seven event listeners by using the following methods:
   - The `completeHandler()` method executes when the image finishes loading.
   - The `httpStatusHandler()` method executes if the image is not loaded locally and only if the network request is made available and the Flash Player can detect it.
   - The `initHandler()` method executes before the `completeHandler()` method and after the `progressHandler()` method. Generally, the `init` event is more useful when loading SWF files.
   - The `ioErrorHandler()` method executes if the image file is not available or not accessible.
   - The `openHandler()` method executes when the image file is first opened.
   - The `progressHandler()` method executes when the image file starts to load and again when the image is finished loading.
   - The `unLoadHandler()` method executes when the image is unloaded by using the `unload()` method when the user clicks the image.

Keep in mind the following requirements:

- This example requires that you place a file named Image.gif in the same directory as the compiled SWF file. Use an image that has an area that fits within the dimensions of the main SWF file.
- Although this example makes use of all events available to the LoaderInfo object, most situations require only a subset. In particular, when loading only an image file, the `complete` event (and perhaps the `ioError` event) are sufficient when loading a local image.

Copy

    package {
        import flash.display.Loader;
        import flash.display.Sprite;
        import flash.events.*;
        import flash.net.URLRequest;

        public class LoaderExample extends Sprite {
            private var url:String = "Image.gif";

            public function LoaderExample() {
                var loader:Loader = new Loader();
                configureListeners(loader.contentLoaderInfo);
                loader.addEventListener(MouseEvent.CLICK, clickHandler);

                var request:URLRequest = new URLRequest(url);
                loader.load(request);

                addChild(loader);
            }

            private function configureListeners(dispatcher:IEventDispatcher):void {
                dispatcher.addEventListener(Event.COMPLETE, completeHandler);
                dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
                dispatcher.addEventListener(Event.INIT, initHandler);
                dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
                dispatcher.addEventListener(Event.OPEN, openHandler);
                dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
                dispatcher.addEventListener(Event.UNLOAD, unLoadHandler);
            }

            private function completeHandler(event:Event):void {
                trace("completeHandler: " + event);
            }

            private function httpStatusHandler(event:HTTPStatusEvent):void {
                trace("httpStatusHandler: " + event);
            }

            private function initHandler(event:Event):void {
                trace("initHandler: " + event);
            }

            private function ioErrorHandler(event:IOErrorEvent):void {
                trace("ioErrorHandler: " + event);
            }

            private function openHandler(event:Event):void {
                trace("openHandler: " + event);
            }

            private function progressHandler(event:ProgressEvent):void {
                trace("progressHandler: bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal);
            }

            private function unLoadHandler(event:Event):void {
                trace("unLoadHandler: " + event);
            }

            private function clickHandler(event:MouseEvent):void {
                trace("clickHandler: " + event);
                var loader:Loader = Loader(event.target);
                loader.unload();
            }
        }
    }

© 2015 Adobe Systems Incorporated. All rights reserved.
Mon Apr 10 2017, 12:28 PM -07:00