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:
-
var _swfLoader:Loader;
-
var _swfContent:MovieClip;
-
-
loadSWF("01.swf");
-
-
function loadSWF(path:String):void {
-
var _req:URLRequest = new URLRequest();
-
_req.url = path;
-
-
_swfLoader = new Loader();
-
setupListeners(_swfLoader.contentLoaderInfo);
-
-
_swfLoader.load(_req);
-
}
-
-
function setupListeners(dispatcher:IEventDispatcher):void {
-
dispatcher.addEventListener(Event.COMPLETE, addSWF);
-
dispatcher.addEventListener(ProgressEvent.PROGRESS, preloadSWF);
-
}
-
-
function preloadSWF(event:ProgressEvent):void {
-
var _perc:int = (event.bytesLoaded / event.bytesTotal) * 100;
-
// swfPreloader.percentTF.text = _perc + "%";
-
}
-
-
function addSWF(event:Event):void {
-
event.target.removeEventListener(Event.COMPLETE, addSWF);
-
event.target.removeEventListener(ProgressEvent.PROGRESS, preloadSWF);
-
-
_swfContent = event.target.content;
-
_swfContent.addEventListener("close", unloadSWF);
-
-
addChild(_swfContent);
-
}
-
-
function unloadSWF(event:Event):void {
-
_swfLoader.unloadAndStop();
-
-
removeChild(_swfContent);
-
_swfContent = null;
-
}
A short addition as many have asked: To dispatch the Event in the loaded SWF just use the following code within your loaded SWF:
-
var _closeEvent:Event = new Event("close", true, false);
-
closeBtn.addEventListener(MouseEvent.CLICK, dispatchUnload);
-
-
function dispatchUnload(event:MouseEvent):void {
-
dispatchEvent(_closeEvent);
-
}
Feel free to ask if any line is not clear or making sense :)



November 11th, 2009
Marvin Blase
Posted in
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
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.
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
[...] [...]
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.
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.
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.
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 :)
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!
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.
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
Hi Marvin, would it be alright to post a link to the code I have for the buttons and loaders here?
Thanks
Justin
hey, for sure - i'll try having a look later then.
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 :)
well, i can't compile without a .fla :)
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!
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?
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.
@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? :)
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.
hey student,
i recently published an article about that. you can check it out.
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!
Have you tried out bulk-loader?
http://code.google.com/p/bulk-loader/
@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".
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,
hey, you can use memstats for this: http://www.beautifycode.com/fps-ms-and-mem-stats
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!
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
What a great resource!
Muchas gracias por el unloadAndStop()... me sirvio de mucho!
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.
Спасибо за ответы на все вопросы :) Действительно узнал много нового. Правда до конца так и не разобрался что и откуда.
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!
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 !
Hi
I have uploaded the swf
My swf plays from the middle when I uploaded it to the website.
What I think happens is that the swf starts playing in the background when the load command is given. It is only visible when we put it on stage through addchild command.
The swf size is about 2.5 MB.
Kindly suggest.
Thanks
Solly
how i make if i want to place button to load swfs.
a.addEventListener(MouseEvent.MOUSE_DOWN, cargaa);
b.addEventListener(MouseEvent.MOUSE_DOWN, cargab);
c.addEventListener(MouseEvent.MOUSE_DOWN, cargac);
function cargaa():void {
loadSWF("a.swf");
}
function cargab():void {
loadSWF("carro1.swf");
}
function cargac():void {
loadSWF("a.swf");
}
i make this but say error 1063. Can you help me.
I understand the 2concern;I am very z sad to hear that you got your Supra fixed. I remember reading about some of your problems5x !.
[...] As3+on click button+load swf file Load & Unload SWF Tutorial (AS3) | Beautify Code Blog this helped me. The next article has information on loading multiple SWF's Reply With [...]
Thank you very much for this tutorial!
I would love for my loader to display the external swf in the center of my main swf. So one question.. is there a way to set the x, y, z for the loaded swf file?
Thank you again!
I used the code and it works perfect. The only issue I ran into is when I have published the file, the SWF would not play. A gray section is shown. Any help?
Thanks.
Q:
is there a way to set the x, y, z for the loaded swf file?
**********************************************************
A:
_swfContent.x = ;
_swfContent.y = ;
_swfContent.z = ;
==========================================================
=====================ANOTHER QUESTION=====================
==========================================================
Q:
... 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?
*******************************************
A:
Pay attention on the string of the code, which is:
_swfLoader = new Loader();
I did the following for the code to work:
|||If you wish to use this script like so you would be able to use it with only just 1 KeyFrame make instead 3 KeyFrames|||
Along with the:
var _swfLoader:Loader;
var _swfContent:MovieClip;
+
_swfLoader = new Loader(); (I cut from the code only this)
Cut & Paste these to the: KEYFRAME 1.
----------------------------------------------------------
Copy & Paste the REST of the whole script
(no second part, e.g. without the code that starts with:
var _closeEvent:Event = new Event("close", true, false);)
to the KEYFRAME 2.
----------------------------------------------------------
Write a code for the KEYFRAME 3:
gotoAndPlay(2);
This is my version of how to set up any variable after defining them, and run them no more than once for the whole time, unless referred to the KEYFRAME 1 once again throughout the coding.
Hope this helps someone.
Ops I forgot to add some of more code here.
Try having this:
KEYFRAME 1:
var _swfLoader:Loader;
var _swfContent:MovieClip;
_swfLoader = new Loader();
var a:Number=0;
--------------------------------------------------------------
KEYFRAME 2:
//I still use MovieClips and then changing them into buttons...
//You may create button from the start [cont]
button1.addEventListener(MouseEvent.CLICK,clickHandlerButton);
button1.buttonMode = true; //[cont] and avoid using this string
function clickHandlerButton(evt:Object):void
{
if (a == 1)
{
//in original code there is a function which performs these commands.
_swfLoader.unloadAndStop();
removeChild(_swfContent);
_swfContent = null;
//You could call that function (haven't tried doing that).
a = 0;
}
if (a == 0)
{
//REST of the code = Refer to the earlier post to know about "REST"
a=1;
}
}
--------------------------------------------------------------
KEYFRAME 3:
gotoAndPlay(2);
--------------------------------------------------------------
That's all.
This solution-code should reload your SWF each time you click on the button1.
[click]
[load]
[click]
[unload]
[load]
[click]
[unload]
[load]
...
Sorry for quite long comment...
Hope this helps and I haven't forgotten anything to mention any more.
I'm using the following code to load a page where I have a gallery. I'm loading the gallery from a SWF file. THis is my first Flash website and I'm having some issues. The page loads fine, the button loads and I click it and the swf file loads. But, it doesn't load in the center of the page...It is off to the top left and it overlaps the home, contact, etc, buttons. THen, when I go to to any other page the swf file continues to play and it won't stop. Can somebody give me some advice...?
The page loads at frame 23 and goes to frame 44. THat's where I have the code below.
stop();
movieClip_1.addEventListener(MouseEvent.CLICK, fl_ClickToLoadUnloadSWF);
var fl_Loader:Loader;
var fl_ToLoad:Boolean = true;
function fl_ClickToLoadUnloadSWF(event:MouseEvent):void
{
if(fl_ToLoad)
{
fl_Loader = new Loader();
fl_Loader.load(new URLRequest("http://www.mywebsite.com/gallerie4website.swf"));
addChild(fl_Loader);
}
else
{
fl_Loader.unload();
removeChild(fl_Loader);
fl_Loader = null;
}
// Toggle whether you want to load or unload the SWF
fl_ToLoad = !fl_ToLoad;
}
stop();
using this code to load unload simple flash games for kids
controls games of some not operating
any ideas
hello there..,
i want to ask you about how to implement this for unloading dynamicly loaded swf..,
what i meant by dynamic is that i just use 1 loader class variable to repeatedly load external swf.this is by done not using simple loop but to wait for each swf loaded and then check if there is still more swf to be loaded, if it is then call the load function again.
thanks..,
I took CNA classes last year, but I wasn't prepared at all for the sheer amount of work involved with being a CNA. The information you provide is really helpful to new students I think, so keep it up.
hi
I have several frames that load external swf and one of them upload a video to youtube but the sound of the video remains in the background when you switch to high-ul swf
could you help me and tell me how to do
thanks
Instead of it loading the movie. How can I make it so that a button loads the movie instead and positions it on a certain area of the stage?
And a silly question, I will be using this in different scenes loading different movie clips. Would I just have to rename the instance and var each time I place it on a new scene? AKA... I'm very new to AS3.
Other then that, this works beautifully!
With havin so much written content do you ever run into any issues of plagorism or copyright violation? My blog has a lot of exclusive content I've either written myself or outsourced but it looks like a lot of it is popping it up all over the web without my authorization. Do you know any methods to help prevent content from being stolen? I'd genuinely appreciate it.
Marvin,
This is $$$! Thank you SO much!
Brad