rss twitter

The finer Art of Loading (#1): Simple load & unload

This one-of-will-be-many-articles is covering the first steps of loading and unloading SWFs properly in Actionscript 3. The follow-up articles will discuss dynamical loading-managements, bulk loading and general questions about caching, the garbage collector and the likes. Well, as said we'll just talking about simple load and a clean unload, as I want to give beginners the chance to follow the upcoming ones and maybe get interested in improving their loading-techniques - as there is much you don't know yet about behind the scenes ;-)

For those interested in loading multiple SWFs and displaying it on click check out #2 of this article series.
The finer Art of Loading (#2): Simple load and display multiple SWFs

So without many words here's the snippet - I hope it is pretty self-explaining. It's written to be directly on a frame in your timeline - as I guess the guys using external classes can adept this snippet for their use, don't they? :) Since FP10 has released many things have been simplified as the unloadAndStop()-method does a good job.

Here we go:

Actionscript:
  1. var _swfLoader:Loader;
  2. var _swfContent:MovieClip;
  3.  
  4. loadSWF("01.swf");
  5.  
  6. function loadSWF(path:String):void {
  7.    var _req:URLRequest = new URLRequest();
  8.    _req.url = path;
  9.  
  10.    _swfLoader = new Loader();
  11.    setupListeners(_swfLoader.contentLoaderInfo);
  12.  
  13.    _swfLoader.load(_req);
  14. }
  15.  
  16. function setupListeners(dispatcher:IEventDispatcher):void {
  17.    dispatcher.addEventListener(Event.COMPLETE, addSWF);
  18.    dispatcher.addEventListener(ProgressEvent.PROGRESS, preloadSWF);
  19. }
  20.  
  21. function preloadSWF(event:ProgressEvent):void {
  22.    var _perc:int = (event.bytesLoaded / event.bytesTotal) * 100;
  23.    // swfPreloader.percentTF.text = _perc + "%";
  24. }
  25.  
  26. function addSWF(event:Event):void {
  27.    event.target.removeEventListener(Event.COMPLETE, addSWF);
  28.    event.target.removeEventListener(ProgressEvent.PROGRESS, preloadSWF);
  29.  
  30.    _swfContent = event.target.content;
  31.    _swfContent.addEventListener("close", unloadSWF);
  32.  
  33.    addChild(_swfContent);
  34. }
  35.  
  36. function unloadSWF(event:Event):void {
  37.    _swfLoader.unloadAndStop();
  38.  
  39. removeChild(_swfContent);
  40.    _swfContent = null;
  41. }

A short addition as many have asked: To dispatch the Event in the loaded SWF just use the following code within your loaded SWF:

Actionscript:
  1. var _closeEvent:Event = new Event("close", true, false);
  2. closeBtn.addEventListener(MouseEvent.CLICK, dispatchUnload);
  3.  
  4. function dispatchUnload(event:MouseEvent):void {
  5.    dispatchEvent(_closeEvent);
  6. }

Feel free to ask if any line is not clear or making sense :)

34 Responses to “The finer Art of Loading (#1): Simple load & unload”

  1. Aiden Tailor says:

    Very good snippet - I like to see you splitting up the different tasks very good (one method does one job) that's best practice.
    I also did not know about the unloadAndStop(); method of the loader class. Kinda wondering why xD

    looking forward to the next posts,
    regards

  2. Marvin Blase says:

    hey there,
    the unloadAndStop()-method has been released pretty late so i guess there are many who do not use it that often. i've made some ram-checks to make sure it's kicked off the cache - and indeed it was completely removed.

  3. Aiden Tailor says:

    till now I just set the loader instance to null, but I guess that's fairly not enough :)
    Will have to rework my preloader class

  4. dbam says:

    pretty / beautify...
    I have to ask You a question,

    _swfContent.addEventListener("close", unloadSWF);

    Where does this "close" event gets dispatched?
    Is it automatic, or "putted in" manually into the event-flow?

    cheers.

  5. Marvin Blase says:

    hey dbam, the close event gets dispatched by any button or whatever in the loaded swf. just write:

    dispatchEvent(new Event("close", true, false));

    this will create a new event and dispatches it - it's bubbling up and therefore reaches the loader-swf.

  6. ectype says:

    Hi. I'm trying to make the transition from AS2 to AS3. If I had a parent swf that loads a child into it and when the child reaches the end of it's animation timeline, is it possible for the child to unload itself on the current index and then load another swf to take it's place on the level or come up one level above it while the one below is unloaded? Right now the swfs merely stack on top of each other. I've tried

    var _swfLoader2:Loader = new Loader();
    addChildAt(_swfLoader2,1);

    _swfLoader2.load(new URLRequest("ch02.swf"));
    stage.removeChildAt(0);

    My example is like a book with chapters that automatically loads the chapters within itself when they reach their respective ends. I know unloadmovienum() is deprecated in AS3 so I'm trying to figure out the best way to execute your example in mine. Thanks in advance.

  7. Marvin Blase says:

    hey ectype - it´s pretty easy. all you need is a count and a function that unloads the current swf and adds another. so basically just dispatch the unload event (just ask, if sth. is not clear :) at the end of your loaded swf to be listened by the loading one. the main-swf is calling a function then (in itself) to unload&add a new one.

    i would try doing it this way:
    create an array which holds the paths to your swfs, so e.g.:

    var swfPathArr:Array = new Array("01.swf", "02.swf", "03.swf");

    whenever a movie is finished you simply raise a count (which starts with 0). so after the 01.swf is done, the count will get 1. this count you use to tell your loading function which index (so: which swfpath) of your array it should load.

    looking above in my code you simply call this loading function after your unloading is done (and therefore already removed from stage if you use my code) with

    loadSwf(swfPathArr[count]);

    what will come up to you is doing a clever preloading-system which preloads the swfs already while the first one is running. but if you can wait some days i'm going to publish it as a little how-to. was going to anyway, so.. hope this helped a bit - otherwise just keep asking :)

  8. justin Moser says:

    Hey, great tutorial! I have one question however, I have 4 buttons which load external swf's when clicked...what i would like to know, is how to make sure that when one button is clicked, all other swfs are removed so that there is only ever one swf on stage, instead of having the swfs piling up on top of each other...

    thanks alot!

  9. Marvin Blase says:

    hi justin,
    are you using the same container ever again? so the simplest thing you could do ist just overwrite the loader's content with the new swf so there will be no chance ever adding 2 swfs at the same time. if you're using multiple containers and loaders you have to iterate through them and delete them by asking if they are not null.

  10. justin Moser says:

    Hi Marvin
    Thanks for that, im loading the swf using url requests into a loader object, for which there is new instances of these loaded when the appropriate button is loaded, so would it be simpler to use the same loader object for each button?

    thanks alot

    Justin

  11. justin Moser says:

    Hi Marvin, would it be alright to post a link to the code I have for the buttons and loaders here?

    Thanks
    Justin

  12. Marvin Blase says:

    hey, for sure - i'll try having a look later then.

  13. justin Moser says:

    hey, thanks a lot, here's the link to the action script class I'm using as the document class for the site this is going to be for:

    http://www.baysickdesign.com/resources/loaders_examplecode.zip

    also, one last question, and its a bit weird, when you look at the code, I wonder if you'd be able to notice why it is, that when the swf is compiled, the second button (Nav2 in the code) only works after the first button has been clicked...weird! Could you let me know please when youve downloaded that, so i can remove it from my server.

    Thanks so much :)

  14. Marvin Blase says:

    well, i can't compile without a .fla :)

  15. justin Moser says:

    ahh ok, here the link to the zip file containing the full document class file, the site.fla, a stats class, and ive replaced the swfs that were loading in, with example ones, as the real swfs contain copyrighted material.

    http://www.baysickdesign.com/resources/Help files.zip

    Thanks alot!

  16. Dee says:

    Hello. I have a quick question?

    Here is a piece of code...

    http://pastebin.com/f62c89941

    My question is:
    How can I call "unloadSWF" if the function loadSWF has been called before?

  17. AS3 student says:

    Hello Marvin Blase,

    Thank you for taking the time to help us ALL out and especially to those of us who are newer and slower at understanding AS3.

    I wanted to ask a couple of things:

    1. Can your code be used with Flash CS3? (Flash Pro 9.)

    2. If #1 is true, then I am trying to figure out how to implement your code using my site architecture and wanted to ask for some clarification.

    I would like to load an initial external.swf then I have nav on the left and would like each of them to unload the current.swf and then load the new.swf associated with that menu section.

    Would you have the time to help point me in the write direction?

    Thank you for your consideration.

  18. Marvin Blase says:

    @dee: you can unload the current swf and AFTER that call the next load-swf. just pass the current swf-params through this bridge-function.

    @as3-student:
    1. yep, for sure! just set it up as an actionscript 3 project.
    2. well, the direction you've got to head is pretty simple. because my snippet allows it to use always the same loader you can easily call the unload-function and after that you need to call the load-function with the swf-path depending on the nav-button you've clicked. well, to be honest this snippet wasn't meant to be universally used for multiple loadings as the preloading-behaviour isn't able to really preload the other swfs. only on calling - but if you're going to be stay tuned for some days i'll try my best to continue this tutorial-series and especially target website-building with external swfs.

    deal? :)

  19. AS3 student says:

    Marvin,
    SO Happy to read your post. THANK YOU for your consideration. I have a good 40 hours of research and still not the best practice example to follow. Your example, and post spoke from someone who knows what they are doing and I understand that if external .swfs are not properly unloaded then the site will just slow down.

    I will be studying up and will keep an eye out on your page here.

    Best,
    AS3 Student.

  20. Marvin Blase says:

    hey student,
    i recently published an article about that. you can check it out.

  21. Alejandro says:

    Great tutorial! I have just one question. What if I want to load the swf inside an empty movieclip? I managed to load it, but how will I have to modify your code in order to unload it?

    Thanks!

  22. Marvin Blase says:

    @alejando:
    mh? just use yourMC.addChild(...) to add the _swfContainer to it. than you can keep on using the unload function as well with yourMC.removeChild(..) - simple as that.

    @jeff:
    for sure, part 3 will cover the beginning of writing that kind of bulk-loader yourself :) but you need some preparation and pre-knowledge to do so - at least i'm not the fan of "here, download and use" but more "learn while read, use it and tell somebody how you've managed it".

  23. Alejandro says:

    Thanks a lot for answering. Actually, I had guessed as much and modified your code to look like this:

    function unloadSWF(event : Event):void {
    _swfLoader.unloadAndStop();
    extContainer.removeChild(_swfContent);
    extContainer._swfContent = null;
    }

    However, I'm not quite sure it's working. How can I check if it is actually removing my loaded swf's from memory?

    Thanks,

  24. shondy says:

    Thanks for the great tutorial. I am however struggling with the part of how dispatching the "close" event works. You said:

    just write:

    dispatchEvent(new Event(“close”, true, false));

    Not sure where that is supposed to go...

    You had a block of code you said to use on the loaded swf:

    var _closeEvent:Event = new Event("close", true, false);
    closeBtn.addEventListener(MouseEvent.CLICK, dispatchUnload);
    function dispatchUnload(event:MouseEvent):void {
    dispatchEvent(_closeEvent);
    }

    I can't seem to get this to work. I created an instance of the close button in the loaded swf, but can't get it to unload the swf.

    Would it be possible to clarify this a bit?

    Thanks!

  25. sam76 says:

    I am working in a linear presentation in which 10swf files load one after another in a main swf movie. I see your code above but not able to do it properly. can you please help by joining the code in which movie load/unload and automatically jump to another swf and so on.

    Thank You Very Much

  26. CNA jobs says:

    What a great resource!

  27. Elkin Siabato says:

    Muchas gracias por el unloadAndStop()... me sirvio de mucho!

  28. Legal Sounds says:

    Pretty good post. I just came across your site and wanted to say that I have really enjoyed reading your opinions. Any way I'll be subscribing to your feed and I hope you post again soon.

  29. Спасибо за ответы на все вопросы :) Действительно узнал много нового. Правда до конца так и не разобрался что и откуда.

  30. Lizzie says:

    Hi Marvin,

    You may have answered this already, but I am pretty slow when it comes to programming with as3. I have a swf that has a button that when clicked, will load an external swf. In the external swf I have an "X" movieclip. Is there a way to have this movieclip make the swf remove itself?

    Thanks!

  31. alex says:

    hey man im a total beginner with programming, flash or actionscript - thats almost 4 days now! im setting up my online portolio site, everythings been great, ure codes finally helped me to work out the separate project clips, and their load/unload buttons! thank you!
    i do have however a small problem. for my main timeline ive found this preloader code that works perfectly:

    this.addEventListener(Event.ENTER_FRAME, loading);

    function loading(e:Event):void{

    var total:Number = this.stage.loaderInfo.bytesTotal;
    var loaded:Number = this.stage.loaderInfo.bytesLoaded;

    bar_mc.scaleX = loaded/total;

    if (total == loaded){
    bar_mc.visible=false
    }

    ...where bar_mc obviously (not for me! :) ) is my preloader clip.

    now when i go to frame 5 i placed your code and my first project portfolio clip loads...but i just cannot embed the above preloader code into yours! i do want to use my bar_mc, not some template progressbar, so what should i do? i keep getting the errors:

    ComponentShim (Compiled Clip), Line 1 5000: The class 'fl.core.ComponentShim' must subclass 'flash.display.MovieClip' since it is linked to a library symbol of that type.

    ComponentShim (Compiled Clip), Line 1 5000: The class 'fl.controls.ProgressBar' must subclass 'flash.display.MovieClip' since it is linked to a library symbol of that type.

    thank you and excuse me for bothering u with such on abvious stupid question !

Leave a Reply

Powered by WordPress | Free T-Mobile Phones for Sale | Thanks to Palm Pre Blog, Video Game Music and Get Six Pack Abs