LoaderMax – Smart AS3 Loading
- Version: 1.4, Updated 2010-09-01
- Compatibility: AS3 (Flash Player 9 or later)
LoaderMax is a new AS3 loading system that does much more than just get swf, mp3, css, video, image, text, binary, and xml files into your Flash application. It eats files for dinner, burps, and then asks for 2nds. And 3rds. Yet it's surprisingly thin. In fact, it can be half the size of most other loading systems even though it delivers a bunch of unique capabilities, some of which you probably never knew you needed but won't want to live without. Here are a few of the noteworthy features:
- Integration of loaders inside subloaded swfs - with most other systems, if you subload a swf, the loader will only concern itself with the swf file's bytes but what if that swf must subload other content like XML, images, and/or other swf files before it should be considered fully loaded? LoaderMax can elegantly handle the sub-subloads as deep as they go. You can link any loader and/or LoaderMax with a swf's root (using the requireWithRoot vars property) so that when you subload it into another Flash application, the parent SWFLoader automatically factors the nested loaders into its overall loading progress! It won't dispatch its COMPLETE event until they have finished as well.
- Automatic parsing of LoaderMax-related nodes inside XML - The XMLLoader class automatically looks for LoaderMax-related nodes like <LoaderMax>, <ImageLoader>, <SWFLoader>, <XMLLoader>, <VideoLoader>, <DataLoader>, <CSSLoader>, <MP3Loader>, etc. in XML files that it loads, and if any are found it will create the necessary instances and then begin loading the ones that had a load="true" attribute, automatically integrating their progress into the XMLLoader's overall progress and it won't dispatch a COMPLETE event until the XML-driven loaders have finished as well. See XMLLoader's ASDocs for details.
- Tight file size - Many other systems are 16-24k+ even if you're just loading text, but LoaderMax can be as little as 7k (depending on which loader types you use).
- Define an alternateURL for any loader - If the original url fails to load, it will automatically switch to the alternateURL and try again.
- A common set of properties and methods among all loaders - All loader types (XMLLoader, SWFLoader, ImageLoader, MP3Loader, CSSLoader, VideoLoader, LoaderMax, etc.) share common properties like: content, name, status, loadTime, paused, bytesLoaded, bytesTotal, and progress as well as methods like: load(), pause(), resume(), prioritize(), unload(), cancel(), auditSize() and dispose() delivering a touch of polymorphism sweetness.
- Nest LoaderMax instances inside other LoaderMax instances as deeply as you want. - A LoaderMax instance is basically a queue of loaders which makes it simple to control them as a whole and get the overall progress, bytesLoaded, and/or bytesTotal. You can put a queue into another - group and nest them however you want. This makes complex queues simple. Need to know when the first 3 loaders have finished loading inside a 10-loader queue? Just put those 3 into their own LoaderMax that has an onComplete and nest that LoaderMax inside your main LoaderMax queue.
- Set a width/height for an ImageLoader, SWFLoader, or VideoLoader and when it loads, the image/swf/video will automatically scale to fit using any of the following scaleModes: "stretch", "proportionalInside", "proportionalOutside", "widthOnly", or "heightOnly". Even crop the image inside that area with crop:true
- Conveniences like auto smoothing of images, centering their registration point, noCache, setting initial x, y, scaleX, scaleY, rotation, alpha, and blendMode properties, optional autoPlay for mp3s, swfs, and videos, and more.
- Works around common Flash hassles/bugs - LoaderMax implements workarounds for things like garbage collection headaches with subloaded swfs, images, and NetStreams as well as other problems like the recently discovered issues with subloading swfs that use TLF.
- Find loaders and content by name or url - Every loader has a name property which you can use to uniquely identify it. Feed a name or URL to the static LoaderMax.getLoader() or LoaderMax.getContent() methods to quickly get the associated loader or content.
- A single loader can belong to multiple LoaderMax instances
- Accurate progress reporting - For maximum performance, set an estimatedBytes for each loader or allow LoaderMax's auditSize feature to automatically preload just enough of each child loader's content to determine its bytesTotal, making progress reporting on large queues very accurate.
- prioritize() a loader anytime - Kick an object to the top of all LoaderMax queues to which it belongs, immediately supplanting the top spot in each one.
- A robust event system - events bubble up through LoaderMax hierarchies and carry a consistent target for easy identification
- Media playback controls in VideoLoader and MP3Loader - convenient methods like playVideo(), pauseVideo(), and gotoVideoTime() as well as properties like playProgress, videoTime, videoPaused, volume, and duration plus useful event dispatching like VIDEO_COMPLETE, PLAY_PROGRESS, and lots more make it simple to wire your own interface to VideoLoader and use it for full playback control, not just loading. Similar controls are available for MP3Loader too.
- Set up multiple event listeners in one line - Add listeners like onComplete, onProgress, onError, etc. via the constructor like new LoaderMax({name:"mainQueue", onComplete:completeHandler, onProgress:progressHandler, onError:errorHandler});
- maxConnections - Set the maximum number of simultaneous connections for each LoaderMax instance (default is 2). This can speed up overall loading times.
- pause()/resume() - no queue loading solution would be complete without the ability to pause()/resume() anytime.
- Helper classes for code hinting and strict data typing - Check out the com.greensock.loading.data package for classes like LoaderMaxVars, ImageLoaderVars, XMLLoaderVars, etc.
- Flex friendly - Simply change the LoaderMax.contentDisplayClass to FlexContentDisplay and then ImageLoaders, SWFLoaders, and VideoLoaders will return content wrapped in a UIComponent.
Rich Shupe debuted LoaderMax in his presentation at Flashbelt (thanks Rich!). You can view his slides here.
Interactive demo 1
Documentation
Please view full ASDoc documentation here.
Sample AS3 code
-
import com.greensock.*;
-
import com.greensock.loading.*;
-
import com.greensock.events.LoaderEvent;
-
import com.greensock.loading.display.*;
-
-
//create a LoaderMax named "mainQueue" and set up onProgress, onComplete and onError listeners
-
var queue:LoaderMax = new LoaderMax({name:"mainQueue", onProgress:progressHandler, onComplete:completeHandler, onError:errorHandler});
-
-
//append several loaders
-
queue.append( new XMLLoader("xml/data.xml", {name:"xmlDoc"}) );
-
queue.append( new ImageLoader("img/photo1.jpg", {name:"photo1", estimatedBytes:2400, container:this, alpha:0, width:250, height:150, scaleMode:"proportionalInside"}) );
-
queue.append( new SWFLoader("swf/main.swf", {name:"mainClip", estimatedBytes:3000, container:this, x:250, autoPlay:false}) );
-
-
//add a loader to the top of the queue using prepend()
-
queue.prepend( new MP3Loader("mp3/audio.mp3", {name:"audio", repeat:2, autoPlay:true}) );
-
-
//prioritize the loader named "photo1"
-
LoaderMax.prioritize("photo1"); //same as LoaderMax.getLoader("photo1").prioritize();
-
-
//start loading
-
queue.load();
-
-
//pause loading
-
queue.pause();
-
-
//resume loading
-
queue.resume();
-
-
function progressHandler(event:LoaderEvent):void {
-
trace("progress: " + event.target.progress);
-
}
-
-
function completeHandler(event:LoaderEvent):void {
-
var image:ContentDisplay = LoaderMax.getContent("photo1");
-
TweenLite.to(image, 1, {alpha:1, y:100});
-
trace(event.target + " is complete!");
-
}
-
-
function errorHandler(event:LoaderEvent):void {
-
trace("error occured with " + event.target + ": " + event.text);
-
}
Interactive demo 2
FAQ
- Where do I get the code?
LoaderMax is included in the main AS3 GreenSock download zip - just click the "Download AS3" button at the top right corner of this page. - What if I need to send variables to the server along with my request in a loader?
The first parameter of the various loaders (ImageLoader, XMLLoader, SWFLoader, MP3Loader, etc.) accepts either a simple String URL or a URLRequest. So if you want to pass data to the server, simply construct a URLRequest accordingly, like:Actionscript:-
var request:URLRequest = new URLRequest("http://www.yourDomain.com/whatever.php");
-
var variables:URLVariables = new URLVariables();
-
variables.exampleSessionId = new Date().getTime();
-
variables.exampleUserLabel = "label1";
-
request.data = variables;
-
request.method = URLRequestMethod.POST;
-
var loader:ImageLoader = new ImageLoader(request, {name:"image1"});
-
- Do I need to define estimatedBytes for all my loaders?
Nope. If you don't define one, the default value of 20000 will be used. The only benefit of defining an estimatedBytes is to make the loader's progress more accurate before it has downloaded enough information to determine the bytesTotal. Once it can accurately determine the bytesTotal, it will do so and stop using the estimatedBytes. By default, when a LoaderMax loads, it will loop through its children first and find any that don't explicitly define an "estimatedBytes" and quickly open a URLStream to determine the bytesTotal if possible. There's a slight speed penalty when the LoaderMax first starts loading, but it makes it very accurate. You can turn that feature off with auditSize:false in your LoaderMax's vars parameter. - If a child loader inside a LoaderMax has already completed and I call load() again on the LoaderMax, will it waste time reloading that already-completed loader?
No. If a loader has completed, LoaderMax will skip it in the queue for maximum efficiency and performance. If you want to force a full reload, though, set the "flush" parameter to true in your load() call, like myLoader.load(true) - Why do I have to use different loader types (ImageLoader, XMLLoader, SWFLoader) instead of LoaderMax automatically figuring out the type of loader needed based on the file name extension?
Actually, LoaderMax has a parse() method that can do exactly that (automatically figure out the type of loader necessary based on the file extension) - you just need to make sure you use LoaderMax.activate() first to activate the loader types that you want LoaderMax to be able to recognize (like ImageLoader, SWFLoader, etc.). This extra step may seem annoying, but there are a few reasons I opted to avoid building the system in a way that activates all of the loader types by default:- It forces ALL types of loaders to be compiled in your swf so that they're available just in case you need them. So your project may never need an SWF loader or MP3 loader, etc. but they still must be compiled in your SWF for the logic in the "lazy" loader. In my opinion, this bloats the whole system which isn't good because a loading system should be relatively lightweight in order to get things moving quickly.
- It's virtually impossible to accurately determine the file type if the extension is something like ".php" because you could have a server-side script that spits back any type - an image, an XML file, etc. In those cases, the "lazy" system would break down. You'd have to explicitly define the type anyway.
Ultimately I believe it is much cleaner to have the developer choose the appropriate loader for the asset whenever possible (ImageLoader, SWFLoader, XMLLoader, etc.) and it definitely allows the system to be more lightweight and efficient. It could literally reduce the file size requirement by more than 60% in many cases.
- Is the LoaderMax API finalized? Might it change?
This is a 1.0 release and while there are no plans to make any changes to the API, my experience has been that feedback from the community is invaluable and can help shape the API. I try to keep improving things to serve end users better, so don't be surprised if there are some changes in upcoming months. I would recommend checking back frequently for updates or sign up for Club GreenSock so that you can be notified. - Can I make suggestions for improving LoaderMax?
Please do! Either in the comments section below or in the forums. - Why did you use the loosely typed vars parameter to define all the special properties (like {name:"myLoader", width:100, height:200}) instead of regular strong-typed parameters or properties? Your way doesn't give me code hinting either.
True. However, one of the objectives was to keep file size to a minimum and encourage readable code, neither of which could be accomplished very well otherwise. There are quite a few optional special properties for various loaders (SWFLoader recognizes 41!) and regular parameters just wouldn't be feasible. Which one is more readable?:Actionscript:-
new SWFLoader("main.swf", "myFile", 100, 100, 200, 200, this, completeHandler, null, null, progressHandler);
-
-OR-
-
new SWFLoader("main.swf", {name:"myFile", x:100, y:100, width:200, height:200, container:this, onComplete:completeHandler, onProgress:progressHandler});
But don't worry - if you want strong typing and code hinting, there are some helper classes for exactly that - Check out the com.greensock.loading.data package for classes like LoaderMaxVars, ImageLoaderVars, XMLLoaderVars, etc. that allow you to define all your vars stuff with a special object.
-
- Can I get the source code for the demos above?
Sure, download it here. - Is LoaderMax available in AS2? Will it be?
The tweening platform and TransformManager, my 2 most popular products, ARE available in AS2 as well as AS3 but LoaderMax is only AS3 because...well...AS2 has been on the decline for a long time and LoaderMax relies heavily on the event system in AS3 so it would be a much bigger challenge to port it to AS2. Then there's maintenance. Right now, every time I make an update to the AS3 version of TweenLite/Max/TimelineLite/Max/TransformManager, I must also make the update to the AS2 versions, copy all the files, create zips, post to the SVN, update the bonus zips for members, etc., Then there are language-specific differences I'd need to accommodate. So it just doesn't seem worthwhile to do for a product like LoaderMax especially since AS2 is heading towards extinction. - Will you be posting more examples?
Yes. - Do I have to purchase a license to use this code? Can I use it in commercial projects?
You may use the code at no charge in commercial or non-commercial web sites, games, components, applications, and other software as long as end users are not charged a fee of any kind to use your product or gain access to it. If your client pays you a one-time fee to create the site/product, that's perfectly fine and qualifies under the "no charge" license. If multiple end users are charged a usage/access/license fee of any kind, please simply sign up for a corporate Club GreenSock membership which comes with a special commercial license granting you permission to do so. Click here for details. Club GreenSock members get several useful bonus plugins, classes, update notifications, SVN access, and more. Please see the licensing page for details on licensing.
Need help?
Please post your question in the forums. You'll increase your chances of getting a prompt answer if you provide a brief explanation and include a simplified FLA file (and any class files) that clearly demonstrates the problem.
Comments (70)

I’m very excited to try the new library out Jack, loving the features you’ve included! Thank you for sharing!
GreenSock have done it again. My life just got a whole lot easier. Thank you!
Amazing work. Again. Thank you so much!
Ah, if only you released this 5 days ago!
Very nice work, I can’t wait to use it in my next project.
Watching Rich demo it now. Thanks, Jack.
I was one of the beta testers on this system, and have had some time to play aound with it on various projects. I truly recommend anyone dealing with web design/development to give it a go. It wil save you a huge load of time and trouble! (Sorry, couldn’t help the pun).
Congratulations! I’m already using it for production while it was beta
, working like charm!
You deserve a medal, Jack!
Wow that was close… I started down the road of creating my own, but I think I will use yours instead!
This is such a great utility and was built smartly. I’ve already started playing with it on multiple levels. Thank you so much!!
Insane feature, it is a kind of bulkLoader, but very better. INSANE
Great stuff (again). They should give out extremely shiny gold stars for this sort of thing. As ever, thanks for sharing all your hard work…
Again ? Jacks seal of quality: Small size and nestable. First TweenLite and now this ? Im a good Coder, but now i have inferiority complexes.
I hate you!
Amazing. Many thanks.
Awesome! Great work as usual guys!
Jack you are the man. This is so well done and sorely needed.
Amazing job! Thanks for all of your hard work!
Fantastic work as always Mr. Green
)
Wow. Make that Wow!
Great, man.
Frikkin awesome!! No more loading pains!!
Awesome!, I’m gonna play with it right now! ;
Very nice, I’ll take a look at it. Maybe this will be a good competitor for the also amazing Arthur Debert’s Bulk Loader (http://code.google.com/p/bulk-loader/).
Saving dev lives left right and centre Jack Doyle – whoever you are! Thanks again!
Been using QueueLoader for most of my previous projects, really looking forward to playing with this though – centering the registration point and setting required w & h before its loaded, hell yeah!
There probably isn’t, but I’ll still ask – Is there any performance penalties in XMLLoader while it checks for LoaderMax specific tag names? And if so, can we disable this?
Silly me – integrateProgress = false to disable XMLLoader looking for LoaderMax related nodes
Haven’t had a chance to work with LoaderMax yet, but just cos it’s from GreenSock I know I’m gonna love it!
Well, after a little look at the LoaderMax i can say that it IS better than the BulkLoader in a lot of ways. It’s like a future version of it for me, plus lots of extras like you always do.
This is going to be a huge hit! You’re doing so much good to the community, Jack. You the man! Adobe should thank you personally and offer a partnership or something!
I love that it can eat seconds, then thirds, and still stay slim! Loving it. Thanks for the lib – looking forward to using it as much as possible.
rocking again, jack!
This is awesome! I will definitly integrate it in the next release of the Fleb Framework (www.flebframework.com)!
Best work, as usual!
Thanks Jack! I already used it while it was beta.
Keep up the great work and make our life easier!
Fantastic Library!
Great job Jack!
Many projects especially those like micro/publicity web apps require all time loads so loads are in some cases my first concern. That’s why I have been working with bulkLoader for a while and I use a class that manage all the load’s that my app requires thru bulkloader and XML.
Now you create this…wow.. it’s like “listening” my methods!? ![]()
Great job Jack!
Nice class ! Very usefull. I will use it in my next projects, for sure. Thanks for sharing
Great tools.I like it.
How can I cast a loaded SWF to a custom datatype (like a baseclass or Interface)
Get rumtime errors when I try…
Got it! This is how:
var myLoadedSWF : MyCustomDataType;
myLoadedSWF = SWFLoader.rawContent as MyCustomDataType;
addChild(_module as DisplayObject);
I wrote my own class a couple weeks ago – MultiLoader… what a waste of time because this kicks my loader’s @$$. I’m proud to be a shockingly green member. Thanks for making my life so much easier.
Once again you guys have rocked it. This is exciting, and I am going to start a new project just as a study in LoaderMax.
Thanks
About Freakn’ time dude!!! I remember a time about a year ago when I asked if you were going to create this. And now you have!
Super awesome job! Best script ever
Brilliant. Magic.
I’ve been wishing and hoping GreenSock would do this for years! I’m so absolutely excited and happy, it raises suspicion.
Awesome! Thank you!
-B
thanks for sharing~~
Awesome! This looks like an awesome preloading class… I can wait to try it out. Thanks for sharing!
Fantastic work…as always
Well… If I needed a kick up the backside to finally switch to as3, then this is it.
Ok jack you’ve finally convinced me.
Fine work.
Thanks for this amazing utility! I’ve been able to overhaul my entire workflow.
This is so awesome, thanks for your efforts!
Feature request: DownloaderMax – Ability to queue up files like this for physical download to local machine with directory structure. Would be absolutely perfect for offline AIR apps that depend on externally loaded content.
Very nice loader solution
Thanks a lot for sharing this !
This is great! I’ve built several loaders overtime, usually in response to a project’s need, and each time have improved on reusability, and features, but haven’t taken it this far. Thanks!!!
Is it possible to pass a parameter to the onComplete handler. Kinda like:
_swfLoader = new SWFLoader(“child.swf”, {parameters:["josé", "joão"], onComplete:_completeHandler});
function _completeHandler(event:LoaderEvent):void {
trace(event.target.parameters);
}
This is brilliant. Kudos, Jack.
Sure, you can use the vars object to store your data, like this:
_swfLoader = new SWFLoader(“child.swf”, {parameters:["josé", "joão"], onComplete:_completeHandler});
function _completeHandler(event:LoaderEvent):void {
trace(event.target.vars.parameters);
}
Hi,
Could you access events in loaderMax?
I would like to know when an element has loaded but not with an onComplete function.
I would like to add an event listener to do that.
Listen to events and take actions based on that.
Thanks
Absolutely, Farnando – LoaderMax is fully compatible with the standard addEventListener() way of working in AS3. The various special properties like onComplete, onProgress, onFail, etc. are simply shortcuts that allow you do set up all those listeners in one fell swoop. It shortens the amount of code you need to write, but feel free to do stuff like this if you prefer:
loader.addEventListener(LoaderEvent.COMPLETE, completeHandler);
Jack, you never cease to amaze!
How are files loaded?
If I add 3 images to the queue, do they start to load all at the same time?
I ask because I would like to be able to load sequentially. One file at a time. Is that possible?
Or do I have to load one file, wait until it’s finished loading and then add the next one to the loader?
LoaderMax gives you complete control over how your queue loads. There’s a maxConnections property that controls how many files it will try to load simultaneously (the default value is 2 which provides a nice mix of prioritization and speed). If you set maxConnections to 1, it will load one file at a time, but loading things sequentially like that is slightly slower because it doesn’t allow Flash to leverage multiple streams at the same time. In other words, if maxConnections is 2 instead of 1, it will finish the overall load of the entire queue a bit faster because it can make better use of your connection.
If you want things to load sequentially one-after-the-other, just set maxConnections to 1, dump all your loaders into the LoaderMax, and let ‘er rip. LoaderMax will handle everything for you.
Jack, thank you so much! You get the high score for karma points, helping out so many embattled coders with such *total* quality software!! What on earth will you do next?
There is some changelog for this module? New version came out, so it would be nice to see what’s new or whats changed in this release without using diff on the source code..
mlemonro, yep, there’s a changelog.txt file in the com/greensock/loading directory.
Loving loaderMax, works soo well and no hiccups. Would love to see an appendURLs method added. That way our array of files could be just the filename without the extension repeating (eg. .jpg). Guess it would only be useful for gallery’s but every bit of text saving counts
var aImages:Array = new Array(“image1″,”image2″); //etc
instead of
var aImages:Array = new Array(“image1.jpg”,”image2.jpg”); //etc
very good framework.
I must spend much time to learn it.
Thank you .
You are the man! Thanks a lot again!!!
well green this is!
Thank you so much for all of your classes. They are extremely well written and easy to use.
I can’t find one project where I won’t use your classes all over the place.
Excellent,good job ……I am enjoying your loader~~
Ridiculously good. Jack takes everything up a level with his tools, and yet somehow makes it simpler as well.
The control and depth of event management for loading is great, the documentation is excellent, the file size trumps all others, and now I get to have my loader, and my tweener living happily under one roof.
Leave your other bloat-loaders behind!








