Preloader in Flash CS3 – Actionscript 3.0 way
14 March , 2007
Posted by on When you want to preload a SWF, JPG,PNG, or GIF in Flash CS3 using Actionscript 3.0 you must use some slightly different way as you did in Actionscript 2.0. The MovieClipLoader class is not used anymore in AS3. Also the loadVars classes are away in Actionscript 3. In this small article I discuss the new way of preloading with a simple example that preloads an image.
I am using the Adobe Flash 9 public Alpha (actionscript preview) for this example which you can download here at the labs.adobe.com site.
Let’s start to have a look at the first lines of the code which is all placed on the first frame of a new Flash 9 document.
All loading stuff is done by the Loader and the LoaderInfo class so let’s import it:
import flash.display.Loader; import flash.display.LoaderInfo;
As you see they are located in the flash.display package. We make an instance of the Loader class:
var myLoader:Loader = new Loader();
The Loader class has a method called load which takes an URLRequest as parameter. So if we want to load something we must first define an URLRequest instance that points to the file we want to load:
var myRequest:URLRequest = new URLRequest("myImageToLoad.jpg");
To use this URLRequest class we also must import it; so at the top of our code we put following code under the import of the LoaderInfo class:
import flash.net.URLRequest;
Now we can use the load method of the Loader class to start load an image on stage and use the URLRequest as parameter:
myLoader.load(myRequest);
Next step is to capture the progress of the loading. This is done by adding eventListeners to the contentLoaderInfo property of the loader object we have instantiated. In this case we use the Event.OPEN, ProgressEvent.PROGRESS and Event.COMPLETE events and we also point to a callback function we want to use:
myLoader.contentLoaderInfo.addEventListener(Event.OPEN,showPreloader); myLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,showProgress); myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,showLoadResult);
As you see we declared three callback functions: showPreloader(), showProgress and showLoadResult. I used the Event constants to describe which event I want to listen for. This implies that we must import these necessary classes so Flash can interprete those specific constants. So at the top of your code write following code:
import flash.events.Event; import flash.events.ProgressEvent;
What we want to do is showing the load progress in a simple textField. But offcourse you can make your own custom preloader if you want; principle is the same. So far so good, thus we need a textfield, lets instantiate one:
var loadProgress_txt:TextField = new TextField();
Again, if we want to use the TextField class we must import it: at the top of your code place following import statement:
import flash.text.TextField;
Ok, now we are ready to write the first callback function that reacts on the OPEN event. In this function we just want to display the textfield. We do this by simply adding it to the displayList:
function showPreloader(evt:Event):void { addChild(loadProgress_txt); }
The second callback function is called when progress during loading is made. In this function we want to show how much is already loaded:
function showProgress(evt:ProgressEvent):void { loadProgress_txt.text = "loaded:"+evt.bytesLoaded+" from "+evt.bytesTotal; }
As you see we can get the bytesLoaded and the bytesTotal propertys directly from the progressEvent. We override the text property of our textField every time progress is made.
The last callback function we must write is the showLoadResult() function. This function only must remove the textField from the displayList and add the content that is loaded to the displayList : so here are the last lines of the code:
function showLoadResult(evt:Event):void { removeChild(loadProgress_txt); addChild(myLoader); }
As you see preloading in AS is a bit different and you have to get used to the new way but ones you get it, it’s fun!
That’s it for now; if you have questions… please leave a comment !
Nice! Saves me (and other readers) the hassle of researching it.
Would this also be used if you had to preload FLVs?
yes it is possible
Thanks, mate!
It was really helpful! I’ve been struggling to update some of my old AS 2.0 code!
Cheers!
Gus
@ Bramus: Nice to see you here mate !
@ nomaeswonk: You can use bytesLoaded and bytesTotal for that (flash.net.NetStream class ) ;-).
@ Gus thanx! Have fun playing AS 3.0 😉
Is it Me – or does Importing every class before it can be used seem just retarded?
hi,
does somebodu have an idea how to implement a preloader in cs3/as3 that loads the main movie, i.e. the movie that the preloader is in?
You would still have to export all linked assets into a frame different than frame 1 to not render a preloader useless, same situation with Flash CS3! But how do you write a simple preloader in frame 1 that uses the Loader Class?
@ sascha/hdrs : Because the instance of the main class of the SWF file has no Loader object, the loaderInfo property is the only way to access the LoaderInfo for the instance of the main class of the SWF file.
Keep getting this error
ReferenceError: Error #1065: Variable request is not defined.
This is my code:
stop();
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.net.URLRequest;
import flash.text.TextField;
import flash.events.Event;
import flash.events.ProgressEvent;
var myLoader:Loader = new Loader();
var myRequest:URLRequest = new URLRequest(“2007_initgroup_home.swf”);
var loadProgress_txt:TextField = new TextField();
myLoader.load(request);
myLoader.contentLoaderInfo.addEventListener(Event.OPEN,showPreloader);
myLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,showProgress);
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,showLoadResult);
function showPreloader(evt:Event):void {
addChild(loadProgress_txt);
}
function showProgress(evt:ProgressEvent):void {
loadProgress_txt.text = “loaded:”+evt.bytesLoaded+” from “+evt.bytesTotal;
}
function showLoadResult(evt:Event):void {
removeChild(loadProgress_txt);
addChild(myLoader);
}
You get that error because your variable request is not defined, you are using it in this line
myLoader.load(request);
and a few lines before you declare your URLRequest variable as myRequest, just change that line for this
myLoader.load(myRequest);
thanx Ponsho, you are my hero ! I corrected the error in the code.
is there any way to pass the properties of the button to the preLoader classes? For example I am loading multiple thumbnails but I want all the thumbnails to have their own preloading bars positioned over themselves.
I am loading one movie after another, and I can get the first movie to hide, but the sound still plays. How do I completely unload the movie?
Hmm….AS3 seems more convoluted! import this and import that just to get some simple things done. Not sure I like it. I’m not an expert programmer and classes sort of snag my brain a little bit but this seems rediculous.
Buddy
Does loading a Flash 8 movie into a cs3 movie causes any problem in the embedded flash 8 movie? like some stuff inside might not work anymore?
@ keneth : yeah that’s indeed true. There is a hack around changing the bytecode at runtime when loading… have a look at : http://www.danielhai.com/blog/?p=35
Thanks for taking the time to post this, it really did help a lot
Thanks for this, it was really useful for me
@Alison, Marie, I want to give back to the community so it was a great pleasure to write this article !
Extremely helpful!! Thank you for saving me hours of research!!
am i the only one getting an 1093 syntax error for this code?
function showProgress(evt:ProgressEvent):void {
loadProgress_txt.text = “loaded:”+evt.bytesLoaded+” from “+evt.bytesTotal;
}
Is there a way of converting this so it loads the whole movie that the preloader is in instead of just one picture?
cw: If you copied and pasted the text from “gazza” you will need to re-type the ” signs
@Chris : take a look at the extra preloading article which you can find at https://newmovieclip.wordpress.com/2007/04/30/more-about-preloading-in-flash-cs3/
There we preload the whole movie !
Is it true this way I can run an external swf, therefore preloading all objects in the library and on the timeline, unlike the “extra preloading article”??
Also another question I have is the bytes loaded stays on 0, any ideas?
Awesome !!!!!!
Now this is what I call vivid information….
Hats OFF man keep up the good work….
Does anyone know how to load multiple swf one after another?
Does anyone know how to load multiple external swfs’ one after another?
Raffi use an array of loader objects. Each one will handle/load one external swf.
Thanks for the script, the first one what was guiding me to good results!
There’s only one problem:
I’m loading a swf file with your preloader, but after finishing, movie is not starting with the first frame. It looks like it is started few seconds before preloader has finished.
I’m really new with Flash Actionscript, so do you have any idea what could be wrong?
Thanks for the info, Parag!
hello,
i am complete new to AS at all.
does this script also load .flv movies?
get the message
Error #2044: IOErrorEvent unverarbeitet. text=Error #2124: Die geladene Datei weist einen unbekannten Typ auf.
(unknow typ)
how can i then adapt this to continue to the 2nd frame, where the website realy starts?
Thanks very helpful. Straight to the point. I still don’t get why they don’t include clear examples like this in with the help files!!!
Hi –
This is great – thanks for posting it. I am slowly learning AS 3.0
One question: This example still seems to work even when I comment out the lines that import the various classes (at the top of the code). So, why then are they needed?
Thanks,
Carl
i’m getting this error…
1093: Syntax error.
loadProgress_txt.text = “loaded:”+evt.bytesLoaded+” from “+evt.bytesTotal;
also ‘1078: Label must be a simple identifier’ for line 24 as shown above.
:O
Im getting the same as konshuss… any recommendations?
figured it out 😛 konshuss if you copy and pasted all the code, make sure you retype the quotation marks 😉
Thank you, Koen. Very generous of you to do this! It works great except I had to adjust the text field (it wasn’t displyaing the loading numbers completely. it was like the text field wasn’t wide enough ) so I had to add this to your code just beneath the var loadProgress_txt:TextField = new TextField();
loadProgress_txt.x = 0;
loadProgress_txt.y = 0;
loadProgress_txt.autoSize = TextFieldAutoSize.LEFT;
(this puts the progress text in the upper left corner. you can adjust the x and y to your needs)
Hope that helps anyone with the same issue!
I’m getting this:
Error #2044: Unhandled IOErrorEvent:. text=Error #2036: Load Never Completed.
Am I doing anything wrong? my code:
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.net.URLRequest
import flash.events.Event;
import flash.events.ProgressEvent;
import flash.text.TextField;
var myLoader:Loader = new Loader();
var myRequest:URLRequest = new URLRequest(“loaded.jpg”);
myLoader.load(myRequest);
myLoader.contentLoaderInfo.addEventListener(Event.OPEN,showPreloader);
myLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,showProgress);
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,showLoadResult);
var loadProgress_txt:TextField = new TextField();
loadProgress_txt.x = 0;
loadProgress_txt.y = 0;
loadProgress_txt.autoSize = TextFieldAutoSize.LEFT;
function showPreloader(evt:Event):void {
addChild(loadProgress_txt);
}
function showProgress(evt:ProgressEvent):void {
loadProgress_txt.text = “loaded:”+evt.bytesLoaded+” from “+evt.bytesTotal;
}
function showLoadResult(evt:Event):void {
removeChild(loadProgress_txt);
addChild(myLoader);
}
Thank you again for this tutorial!
Hi,
Is there a way to get the size of an image to be loaded without actually loading it? I’m creating a gallery of images, with a Loader for each image (I created a class with all the necessary info for each image, including url, loader, etc…) and I want to be able to show the progress of loading the entire gallery as x% of total. Thanks in advance!
J
Thank you for the pre_loader code. I learned so much from that.
Regarding Ronny’s question:
Yes indeed, movies starts as soon it is initialized
and before contentLoaderInfo’s Event.COMPLETE is raised.
The obvious thing you could do is to put stop() command in the first frame of loaded swf.
More elegant solution, allowing that swf to start normally when run without preloader is to do the following:
myLoader.contentLoaderInfo.addEventListener(Event.INIT ,initHandler);
function initHandler(e:Event) {
MovieClip(LoaderInfo(e.target).content).stop();
}
Don’t forget:
function showContent(event:Event):void {
removeChild(myPreloader);
addChild(myLoader);
MovieClip(LoaderInfo(event.target).content).play();
}
at the end to start playing the loaded movie once MovieClip(LoaderInfo(event.target).content).stop(); has been called.
Thanks! I save lot of time,
Pingback: Davey’s Flash Blog » Blog Archive » Transitioning from AS2 to AS3: Preloading Movies
Nice code 🙂
Thx a lot! Will save me some time for my flash project :p
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.net.URLRequest;
var myLoader:Loader = new Loader();
var myUrlReq:URLRequest = new URLRequest(“image_effect.swf”);
myLoader.load(myUrlReq);
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaded);
function onLoaded(event:Event):void
{
var rollover_animation:Class = event.target.applicationDomain.getDefinition(“rollover_animation”) as Class
var myMovieClip:MovieClip = new rollover_animation() as MovieClip;
addChild(myMovieClip);
}
Plz check for me, I have errors “1120 Access of undefined property myLoader”
@Mars, I tested your code here and it’s working for me… strange..if you send me your files, I will have a look at it..
Im getting syntax errors… whats up here? Could someone maby post a working code?
stop();
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.net.URLRequest;
import flash.text.TextField;
import flash.events.Event;
import flash.events.ProgressEvent;
var myLoader:Loader = new Loader();
var myRequest:URLRequest = new URLRequest(”flash.swf”);
var loadProgress_txt:TextField = new TextField();
myLoader.load(request);
myLoader.contentLoaderInfo.addEventListener(Event.OPEN,showPreloader);
myLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,showProgress);
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,showLoadResult);
function showPreloader(evt:Event):void {
addChild(loadProgress_txt);
}
function showProgress(evt:ProgressEvent):void {
loadProgress_txt.text = “loaded:”+evt.bytesLoaded+” from “+evt.bytesTotal;
}
function showLoadResult(evt:Event):void {
removeChild(loadProgress_txt);
addChild(myLoader);
}
Great info! Works perfect!
Great job man!
Help me a lot!!
Thnx
Pingback: Proloader im ersten Schlsselbild - PSD-Tutorials.de - Forum
hey great posting! I was wondering what I would need to chance to preload my entire site? Thanks
This is perfect, thank you for sharing! 🙂
Thanks a lot for the tip. I needed a fast solution and I got it here. Though I initially wanted to include the code that does the preloading in the same file as the swf I intended loading, but I think I’d create the preloader separate from the main swf file.
Thanks.
Thanks for the information on preloading content for ActionScript 3, Koen. I was wondering why ActionScript 3 does not generate a compiler error when commenting out the import directive lines. The Flash CS3 help documention reads the follwing for import directive:
“Makes externally defined classes and packages available to your code. For example, if you want to use the flash.display.Sprite class in a script, you must import it. This requirement is different from previous versions of ActionScript, in which the import directive was optional.”
They make it sound as if it is required to specify imports for AS3. So, why doesn’t the compiler generate an error when I comment them out? Or, am I misunderstanding something here?
i m new but i got it. nice dear
Pingback: MMUG-Dublin Bloggers » Actionscript 3 Preloading/Loading a large video file
i am making a flash flip meny and prb is loading
that is attached with xml file ,xml file having 42 jpg pages
now it will display when all 42 pages downloaded
i want when 2 or 4 page will downloaded it will display and rest of the pages will download back side
right now i am using this script.
stop();
var nocache = new Date().getTime();
_quality = “BEST”;
Stage.scaleMode = “noScale”;
onEnterFrame = function() {
LB = getBytesLoaded();
TB = getBytesTotal();
PC = (LB/TB)*100;
loaderbar.setbar(PC);
if(TB>4 && PC == 100) {
delete onEnterFrame;
gotoAndPlay(“initialize”)
}
}
// specify content source
if(_level0.xmlFile==undefined) {
_level0.xmlFile = “xml/pages.xml”;
}
please tell me how can i do that thing
Hello! Firstly, thnak you – this initial tutorial was exactly what I needed (am new to AS3 it it has worked perfectly!!!) – I would like to be able to load this external file into an MC, (since I only want to use a little of the screen for it) – is this possible? Ive tried to use the old AS2 of target_mc but I cant work it out!
Any advice would be most welcome, but even so – thank you, this was a really well written article (even I understood it!).
scotia 🙂
I re-iterate James question above which sadly hasn’t been answered and can’t find anything about it anywhere! Can you determine the length or width of a file before loading it? The reason I ask is some of my images are landscape and others are portrait and they are required to fit into a frame on my stage. Sadly I cannot do this. I can position the loader but it changes for the different images… any help as to how to solve this one would be a huge! Here’s to hoping… NIce tutorial!
Hi there. Helpful preloading tutorial, but when running it to load a big jpg, the loadProgress_txt.text jumps from 0 directly to the total amount of bytes (when the image is fully loaded). Using trace in the showProgress event, reveals this event is fired multiple times as it should (with hops of 65536 bytes), but only generates output when the image is fully loaded. How can the progress text be updated as the image is gradually loading please? Any help would be appreciated.
Please ignore my previous reply. Problem solved when running on server.
love is a gameble.
sex is a game.
boys do the fucking.
girls get the pain.
one night of pleasure.
nine months of pain.
three days in the hospital.
one baby to name.
Cherry Red Casino
Thanks, Its working.
Sweet. I finally got it working after being afflicted with the 1009 error for a bit. Here’s what fixed it for me (above comments were quite helpful).
My main AS3 class definition that is using the preloader had a line that added an event listener to the stage:
stage.addEventListener(MouseEvent.MOUSE_MOVE, cursorFollow);
This was in the constructor and caused the 1009 error because it wasn’t on the stage yet.
=== Here’s how I fixed it: ===
Replace the above code with an event listener that triggers when the object is added to the stage:
addEventListener(Event.ADDED_TO_STAGE, addStageListener);
Then add the stage event listener in in that separate function:
function addStageListener(evt:Event):void {
stage.addEventListener(MouseEvent.MOUSE_MOVE, cursorFollow);
}
Great exemple of how use a preloader whle the main application access to the Stage !
Thanks a lot to share your tricks
regard
Pingback: links for 2009-02-21 | Visualrinse | Design and Development by Chad Udell
Pingback: links for 2009-02-21 | Iona.LABS
Pingback: [Flash] Preloader in Flash CS3 - Actionscript 3.0 | Billyblue Entertainment
dankuwel Koen!
Thanks Koen!
I’ve been at this for days!!!
Multiple websites and none of the code works. Just blows me away!
On the dynamic text field, what instance name do I give it? loadProgress_txt ??????????????????????????????????
Here is my code and yes I changed the quotation marks in the code.
I would be EXTREMELY GRATEFUL for any help on this!!! 🙂
1151: A conflict exists with definition loadProgress_txt in namespace internal.
stop();
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.net.URLRequest;
import flash.text.TextField;
import flash.events.Event;
import flash.events.ProgressEvent;
var myLoader:Loader = new Loader();
var myRequest:URLRequest = new URLRequest(“about_index.swf”);
var loadProgress_txt:TextField = new TextField();
myLoader.load(myRequest);
myLoader.contentLoaderInfo.addEventListener(Event.OPEN,showPreloader);
myLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,showProgress);
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,showLoadResult);
function showPreloader(evt:Event):void {
addChild(loadProgress_txt);
}
function showProgress(evt:ProgressEvent):void {
loadProgress_txt.text = “loaded:”+evt.bytesLoaded+ ” from ” +evt.bytesTotal;
}
function showLoadResult(evt:Event):void {
removeChild(loadProgress_txt);
addChild(myLoader);
}
Grateful for sites like this and all the efforts to teach us newbies! 🙂 Though the code didn’t work for me…it doesn’t mean it doesn’t work. I’m sure it does. I did go to another site and found this code. It had a video and .fla files and code seemed simple.
I wanted to share the link because I’ve at this for days and I finally got the code that works for me. 🙂
I found this code on http://theflashblog.com/?p=438
This works perfect! Maybe I just needed to see a video…
var l:Loader = new Loader();
l.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loop);
l.contentLoaderInfo.addEventListener(Event.COMPLETE, done);
l.load(new URLRequest(“content.swf));
function loop(e:ProgressEvent):void
{
var perc:Number = e.bytesLoaded / e.bytesTotal;
percent.text = Math.ceil(perc*100).toString();
}
function done(e:Event):void
{
removeChildAt(0);
percent = null;
addChild(l);
}
@Bryon: Did you already create a text field named “loadProgress_txt” in the frame prior to entering the code? If so that might be the source of the conflict.
Nice simple article, exactly what a tutorial should be all about. Brilliant!
thanks a lot!!!! i’m italian but your lesson was so simply that i understood perfectely what to do!!! you’re great
very very nice! thanks
Why did Adobe make AS that much more complicated. I hate all the extra code you have to put in for something that is so common, it should be 2 mice clicks by now for the action to occur.
I have been searching via google for over an hour now looking for a preloader for a 3 frame flash file that is simply a loading frame, the frame that houses the FLV to be played, and a third frame for when the FLV is done to go to with a button.
It took 3 hours to finally find a tutorial that worked for the last two frames to work, but for the life of me i cant find a preloader that works. I dont code. I dont. It seems that Adobe wants to take the creativity away from artists (with all the cookie cutter out of box filters and tools for graphics programs), and force everyone to become hard core coders. It shouldnt be more than 3 lines of very simple code to freaking preload X amount of bytes of an FLV before it plays. How hard is it to copy and paste something and have it work?
Hi,
thanks for your great code.
why you don’t use GeSHi ?
Hey thanks for the code! This is killer dude, I’ve been stuck for hours. Thanks again!
Very useful post. If the user wants to replay the video would it run the pre-loader again?
This was for Disney Magic Kingdom and had so many fast and easy ways to spruce up your scrapbooking pages. Am really impressed and would like to get some of the other Finish in a Flash page kits.
newmovieclip.com has potential, you can make your blog go viral easily
using one tricky method. Just type in google:
Kimting’s Method To Go Viral
NIKE story