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]

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

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

  • http://cksachdev.blogspot.com cksachdev

    cool introduction to loader ..

  • http://voices.mv mode

    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?

  • http://drawlogic.com/ drawk

    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.

  • bobcat goldthwait

    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?

  • http://drawlogic.com/ drawk

    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/

  • http://www.xsn.com.au Xavier

    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

  • http://drawk.com/ ryan

    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.

  • Ashok

    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

  • common sense

    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.

  • http://www.sivumedia.fi coderx

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

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

  • http://sambrera.ru Таракан

    Нифтяк!

  • luke

    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”);

  • http://www.choosetory.com ToryHargro.com

    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!

  • Sosh

    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.

  • ks61

    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?

  • http://drawlogic.com/ drawk

    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.

  • ks61

    Thanks for yor reaction, but …

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

  • http://drawlogic.com/ drawk

    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…

  • ks61

    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?

  • ks61

    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);
    }

  • ks61

    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);
    }

  • ks61

    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);
    }

  • DDDDepressionnnn

    Depression Depression Depression aaaaaaaa
    HEEEEELP :( :( :(
    I hate winter! I want summer!

  • wintervssummer

    I very much love summer :)
    Someone very much loves winter :(
    I Wish to know whom more :)
    For what you love winter?
    For what you love summer? Let’s argue :)

  • http://www.delay.pl/ Dominik

    Hi!
    Thanks for this! I got one question and would be really happy if you knew the answer.

    i’m loading 50 thumbs at once. Listener is set.
    thumbLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,thumbsLoaded);

    i want to know name of just loaded loader

    function thumbsLoaded(evt:Event):void
    {
    thumbLoader.name ??
    }

    all i figure out so far is i can see file url through contentLoaderInfo like this
    trace(evt.target.url);

    it would be great if there was a chance to set name of that loader and later get it when it’s loaded.

    any hints ?

    cheers
    Dominik
    http://www.delay.pl/

  • http://drawk.com drawk

    Dominik,

    You probably want to write up us use something like http://code.google.com/p/bulk-loader/. This will help you with large sets of data to load and finding them.

  • http://flashduniya.com hr

    if the requested URL not found then I want to load my default file
    Can you please tell me the code for that

  • Pingback: codebabes.log - we’ve got curves and compilers

  • http://buildi.ru dawduefgelf

    Хорошо пишете. Надеюсь, когда-нибудь увижу нечто подобное и на своем блоге…

  • http://prmobilnik.ru helefyv

    Хорошо пишете. Учились где-то или просто с опытом пришло?

  • http://mobilnikru.ru virabux

    Очень интересно. Но чего-то не хватает. Может быть, стоит добавить каких-нибудь картинок или фото?

  • http://sport-v.ru hebygaf

    Вот решил вам немного помочь и послал этот пост в социальные закладки. Очень надеюсь ваш рейтинг возрастет.

  • http://wchild.ru kefasot

    Блог в ридер однозначно

  • http://booksz.ru wechate

    Добавил в свои закладки. Теперь буду вас намного почаще читать!

  • jloa

    Guys, those that needed to re-use e.i. make a copy of a loader after load – grab my LoaderUtil class
    the class archived: http://chargedweb.com/labs/files/LoaderUtil.zip
    find more useful stuff at my labs.

    Cheers

  • jloa

    Guys, those that needed to re-use e.i. make a copy of a loader after load – grab my LoaderUtil class
    the class archived: http://chargedweb.com/labs/files/LoaderUtil.zip
    find more useful stuff at my labs.

    Cheers