HOWTO: Using Loaders in AS3

What are these ominous Loaders is what people ask when they first start into AS3?  Loaders help to facilitate the loading of sprites or content that aren’t in the DisplayObjectList tree just yet.  Loaders allow you to load all types of files swf, jpg, png, etc and put them right in the display list.  A very simple basic load is below to describe the basics of loading content.  This can be used many ways within individual classes or shared and add in multiple file downloading.  You might add zip file downloading and then automatic upzipping of assets to load in.  There are many ways to architect your downloading and preloading but this is the basics of a loader in AS3.

var request:URLRequest = new URLRequest("content.swf");
var loader:Loader = new Loader();

loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loadProgress);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);

function loadProgress(event:ProgressEvent):void {
var percentLoaded:Number = event.bytesLoaded/event.bytesTotal;
percentLoaded = Math.round(percentLoaded * 100);
trace("Loading: "+percentLoaded+"%");
}
function loadComplete(event:Event):void {
trace("Complete");
}

loader.load(request);
addChild(loader);

All DisplayObject instances have a loaderInfo property consisting of a LoaderInfo instance that provides information about that object’s loaded content (if applicable). The Loader instance contains this property along with an additional contentLoaderInfo property which represents the LoaderInfo instance of the content being loaded. When loading content into a Loader, the contentLoaderInfo property is the object you would want to add listeners to for information about the loaded content such as when new bytes are being loaded into the player (for a preloader) and when loading has completed.

The events associated with LoaderInfo instances includes:

  • complete:Event — Dispatched by the associated LoaderInfo object when the file has completed loading. The complete event is always dispatched after the init event.
  • httpStatus:HTTPStatusEvent — Dispatched by the associated LoaderInfo object when a network request is made over HTTP and Flash Player can detect the HTTP status code.
  • init:Event — Dispatched by the associated LoaderInfo 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 associated LoaderInfo object when an input or output error occurs that causes a load operation to fail.
  • open:Event — Dispatched by the associated LoaderInfo object when the loading operation starts.
  • progress:ProgressEvent — Dispatched by the associated LoaderInfo object as data is received while load operation progresses.
  • unload:Event — Dispatched by the associated LoaderInfo object when a loaded object is removed.

[source]

Advertisements

26 Responses to “HOWTO: Using Loaders in AS3”

  1. GadgetGadget.info - Gadgets on the web » Blog Archive » HOWTO: Using Loaders in AS3 Says:

    […] darmano wrote an interesting post today!.Here’s a quick excerptvar request:URLRequest = new URLRequest(”content.swf”); var loader:Loader = new Loader(); loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loadProgress); loader.contentLoaderInfo.addEventListener(Event. … […]

  2. AS3 BulkLoader Useful Flash Asset Loading Kit by Arthur Debert « [ draw.logic ] Says:

    […] AS3 Loaders are very useful, but when you have large projects there is always a pause and focus on loading scenarios and architecture needed for your loading scenarios, sometimes this can literally eat days and entirely change performance with wrong moves. BulkLoader is a well written kit from Authur Debert that makes loading scenarios or using BulkLoader as a base to your loading situations a great pluggable piece of code that has many excellent features. […]

  3. cksachdev Says:

    cool introduction to loader ..

  4. mode Says:

    kewl
    so if i wantd to load an external swf and display it twice on the screen, with different dimensions, how could that be done? could i make a copy of the loader?

  5. drawk Says:

    Mode you could load the content into two Sprites. So instead of just addChild you would first add a sprite, then another and attach it to those, then add them to the main stage. Then you can size the Sprites as containers.

  6. bobcat goldthwait Says:

    I have a list of images that i’ve looped overand loaded with the Loader class, but I’m having a tough time assigning them unique names.
    I want unique names because I want to know what loader the user clicks on (using mouse event handling).
    Is there a way to assign loaders a name or some unique tag so i can retrace what the user clicked on?

  7. drawk Says:

    Sounds like you need aurthur debert’s bulk loader. This makes handling many loaders very simple.

    http://www.stimuli.com.br/trane/2007/nov/25/loading-reloaded/

  8. Xavier Says:

    Hey all, what do i do if i have an exsisting movie clip, and i want to load an external swf from a url into it?

    Thanks

    Xavier

  9. ryan Says:

    You can do it in the movieclip but if you need to do it from the container (load one in then load another movie into that) you will have to get a reference to it and then you can just [obj].addChild like any other object. There are lots more ways to do it, it really depends on where the controller is at. This sample loads into itself, you can easily get the loader and add the child to an object already in your stage or loaded in.

  10. Ashok Says:

    hi ,

    I have an issue .I have to load an dynamically load images into movie clip in flash cs3 as3.

    The code is available in the link: http://drawlogic.com/2007/09/20/howto-using-loaders-in-as3/

    with the code

    1. var request:URLRequest = new URLRequest(“content.swf”);
    2. var loader:Loader = new Loader();
    3.
    4. loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loadProgress);
    5. loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
    6.
    7. function loadProgress(event:ProgressEvent):void {
    8. var percentLoaded:Number = event.bytesLoaded/event.bytesTotal;
    9. percentLoaded = Math.round(percentLoaded * 100);
    10. trace(“Loading: “+percentLoaded+”%”);
    11. }
    12. function loadComplete(event:Event):void {
    13. trace(“Complete”);
    14. }
    15.
    16. loader.load(request);
    17. addChild(loader);

    But only one image can be uploaded I want to load External IMAGES into a Movie Clips.

    Pease help me in this.

    With Regards
    AShok

  11. common sense Says:

    if you read event descriptions above, INIT is when the external is actually in a ‘ready’ state… COMPLETE you would use to inject variables required into an external asset if they were desired/required.

  12. coderx Says:

    good tutorial, just if addChild() could be in loadComplete -function.

    And your pages look WERY PERFECT!!!!! in my taste..

  13. luke Says:

    hey there, think someone else had this question as well re: using loaders to load images into two different places. but i’ve tried using sprites, attaching the loader to the sprite, then the sprite to the MC, and it still doesn’t work – when i call loader again, the first image disappears. 🙂 i’ve got it working with the code below, but i’m sure this can be improved. any suggestions?

    // load in images dynamically
    var leftloader:Loader = new Loader();
    leftloader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loadProgress);
    leftloader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
    var rightloader:Loader = new Loader();
    rightloader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loadProgress);
    rightloader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);

    function loadProgress(event:ProgressEvent):void {
    var percentLoaded:Number = event.bytesLoaded/event.bytesTotal;
    percentLoaded = Math.round(percentLoaded * 100);
    trace(“Loading: “+percentLoaded+”%”);
    }
    function loadComplete(event:Event):void {
    trace(“Complete”);
    }

    var curimg=0;
    function loadImage(thisframe) {
    curimg++;
    var request:URLRequest = new URLRequest(“images/img”+curimg+”.jpg”);
    if (thisframe==”leftframe”) {
    leftloader.load(request);
    leftframe.holder.addChild(leftloader);
    trace (“load left”);
    } else {
    rightloader.load(request);
    rightframe.holder.addChild(rightloader);
    }
    }
    loadImage(“leftframe”);

  14. ToryHargro.com Says:

    Hey Guys, I’m having a huge problem with loading an external .swf that includes an FLV video file. No matter what I do, myoader.unload(); or myloader.removeChild(); Nothing seems to make the video stop playing. It’s dissappears but the audio continues to loop in the background,

    I managed to patch this using the flash.media.SoundMixer.stopAll(); methoid but this is ONLY a patch. My memory is getting killed!

    It appears adobe knows about this problem but please tell me someone has a solution!

  15. Sosh Says:

    So, what you end up with is an object of type Loader? And you then use that like a sprite or movie clip? That’s pretty ugly. Would have been better if the loader mechanism left you with a sprite or something.

  16. ks61 Says:

    In actionScript 2.0 i used to load movies at level_0 to replace original. How can i do that with a loader?
    Must i (can i) unload the parent?

  17. drawk Says:

    Hey ks61,

    Yes the new Display Object Tree allows you to load in objects into the display tree with addChild() on amy movie clip or the stage. If you addChild it will simple append the object. If you want to clear out the old one you can removeClip() or removeClipAt(index) before loading in the same location. You can removeClipAt(0) for clips that have no children to remove it from the display tree.

  18. ks61 Says:

    Thanks for yor reaction, but …

    removeClip() and removeClipAt() are not standard Flash actions are they?
    I cannot find them in the help-function.

  19. drawk Says:

    Oh man I can’t believe I said that.. hehe working on some AS2 with old school removeClip. Sorry yes it is removeChild() and removeChildAt() they are part of any object that inherits from DisplayObject such as flash.display.MovieClip. The whole display object tree is based on objects with children. So it is addChild and removeChild etc. Sorry for the confusion, late…

  20. ks61 Says:

    tried and tried …

    with removeChildAt(0) i remove a child in the loaded movie
    with parent.removeChildAt(0) i expected a small success but instead Flash crashes. (for some of you that maybe very logical, i simply copied it from another forum)

    there is no such thing as removeParent()

    A solution may be to start with an empty movie that loads another movie in a targetclip. The loaded movie can with a mouseclick load another movie in the targetclip. Sounds simple, but does not work as i expect it. Any suggestions?

  21. ks61 Says:

    A solution may be to start with an empty movie that loads another movie in a targetclip. The loaded movie can, with a mouseclick, load another movie in the targetclip. Sounds simple, but does not work as i expect it. Any suggestions?

    i tried this:

    loadOther_btn.addEventListener(MouseEvent.MOUSE_UP, loadOther);

    function loadOther(event:MouseEvent):void {
    parent.request = new URLRequest(“otherMovie.swf”);
    parent.loader.load(request);
    }

  22. ks61 Says:

    tried and tried and found it:

    var mRequest:URLRequest;
    var loader:Loader= new Loader();

    load400_btn.addEventListener(MouseEvent.MOUSE_UP, loadOther);

    function loadOther(event:MouseEvent):void {
    removeChildAt(0)
    mRequest = new URLRequest(“otherMovie.swf”);
    loader.load(mRequest);
    addChild(loader);
    }

  23. ks61 Says:

    Another correction (the final one it seems) because you need to remove ALL children, in the other example i removed just one:

    var mRequest:URLRequest;
    var loader:Loader= new Loader();

    loadOther_btn.addEventListener(MouseEvent.MOUSE_UP, loadOther);

    function loadOther(event:MouseEvent):void {
    while (numChildren>0)
    {
    removeChildAt(0);
    }
    mRequest = new URLRequest(“otherMovie.swf”);
    loader.load(mRequest);
    addChild(loader);
    }

  24. Anonymous Says:

    I like to disseminate information that will I have accrued through the
    year to help improve team performance.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: