Get GSAP

Version: 1.14.2 updated 2014-10-29

Core

    Extras

      Plugins

        By using GreenSock code, you agree to the terms of use.

        LoaderMax

        LoaderMax is an AS3 loading system that does for loading what TweenLite and TweenMax did for tweening, simplifying and enhancing the entire process. LoaderMax 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 surprising number 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:

        • Integrated subloaders - LoaderMax can recognize other LoaderMax-related loaders inside an asset being loaded and integrate them into the overall loading progress and the event model of the main loader. For example, if LoaderA subloads LoaderB which subloads LoaderC, LoaderA can report the entire group's progress and not dispatch its COMPLETE event until LoaderB and LoaderC have finished loading (see the ASDocs about the "requireWithRoot" special property to enable this feature).
        • Flexible setup - build loaders in a variety of ways, including single-item loaders from nothing more than a URL (LoaderMax can automatically determine which type of loader to use based on the file extension) and loader queues automatically assembled from XML documents or an array of URLs.
        • Prioritize on the fly - build a queue that intelligently loads assets in the order specified but that can easily reprioritize any asset anytime. For example, if the user clicks something that requires loading immediately, just prioritize() its loader.
        • 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).
        • Detailed progress reporting - show progress of individual loaders or groups of loaders.
        • Robust event system - easily add event listeners, including multiple listeners in a single line of code. Events bubble up through LoaderMax hierarchies and carry a consistent target for easy identification.
        • Define an alternateURL for any loader - If the original url fails to load, it will automatically switch to the alternateURL and try again.
        • Avoid common Flash bugs/hassles - LoaderMax solves many problems like the recently discovered issues with subloading swfs that use TLF as well as garbage collection headaches with subloaded swfs, images, and NetStreams.
        • Pause and resume loads in progress
        • Conveniences galore - prevent asset caching, optionally manipulate many display characteristics like image smoothing, centering registration points, positioning, and many more. 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 asset inside that area with crop:true
        • Common set of properties and methods - all loaders types (XMLLoader, SWFLoader, ImageLoader, MP3Loader, CSSLoader, VideoLoader, LoaderMax, etc.) have name, status, loadTime, paused, bytesLoaded, bytesTotal, and progress properties as well as methods like load(), pause(), resume(), prioritize(), unload(), cancel(), auditSize() and dispose() delivering a touch of polymorphism sweetness.
        • Media playback controls in VideoLoader and MP3Loader - operationally control video and MP3 assets including methods that play, pause, and go to a specific time; properties that get or set volume, time, and duration; and events that monitor playback progress and more.
        • Automatic parsing of LoaderMax-related nodes inside XML - XMLLoader can look for LoaderMax-related nodes like <LoaderMax>, <ImageLoader>, <SWFLoader>, <XMLLoader>, <VideoLoader>, <DataLoader>, <CSSLoader>, <MP3Loader>, etc. inside XML files that it loads, and if any are found it can create the necessary instances and then begin loading any that had a load="true" attribute, integrating them into the XMLLoader's overall progress. See XMLLoader's ASDocs for details.
        • 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 or report their progress as a whole. You can put one queue into a slot inside another - group and nest them however you want. This makes complex queues simple.
        • 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 from anywhere.
        • maxConnections - Set the maximum number of simultaneous connections for each LoaderMax instance (default is 2). This can speed up overall loading times.
        • 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.

        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/child.swf", {name:"childClip", estimatedBytes:3000, container:this, x:250, autoPlay:false}) );
        queue.append( 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();
         
        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

        Avoid bugs, inconsistencies, and hassles

        Reliability is a huge concern when it comes to loading external assets. Did you know there are a bunch of bugs, inconsistencies, and hassles in Adobe's loading classes (Loader, URLLoader, NetStream, and Sound) that could cause trouble in your project? This is another reason why so many developers are shifting to LoaderMax - it works around these issues and provides a more stable, reliable, and robust foundation for loading. Use LoaderMax to avoid these issues:

        • Adobe's Loader doesn't properly subload swf files that use Adobe's TLF. The preloading animation stays on the screen and the Loader's "content" doesn't refer to the real swf root, so reference errors are generated. See Adobe's note here. See example here..
        • When MouseEvent listeners are added to swf content loaded by Adobe's Loader, they are not dispatched properly (at least when the swf was published by CS5). See example here..
        • If close() is called on a Loader before its INIT event is dispatched, the content may not be properly unloaded or garbage collected.
        • If BitmapData.draw() is called on a partially-loaded child swf that contains a NetStream that hasn't started yet, SECURITY_ERRORs are thrown.
        • If close() is called on an in-progress Loader, its bytesLoaded reports incorrectly on all subsequent loads even for completely different files. It cannot be reused effectively.
        • In certain browsers, a Loader or URLLoader's bytesLoaded is occasionally reported as being greater than bytesTotal (impossible) when gzip is enabled on the server. This can lead to the progress never reaching 1.
        • Subloaded swf files may not be properly unloaded or garbage collected if all nested MovieClips aren't stopped first and even if they are, the swf may not unload properly. It can be particularly problematic if the child swf has audio that's attached to the timeline as a "stream".
        • If pause() is called on a NetStream before the metaData is received (client.onMetaData() is called), it will never be received even after the NetStream resumes.
        • If Video.attachNetStream() is called when the NetStream's buffer is full, the NetStream doesn't attach properly (it doesn't display). (See example FLA)
        • Video.attachNetStream() doesn't work properly when called as the video is added to the display list with addChild() unless you seek() at the same time. That seek() cannot be to a time after the last encoded keyframe either or it won't work. (See example FLA)
        • If NetStream.pause() is called when the NetStream isn't attached to a Video object and the buffer isn't full, it acts as though it continues playing (ignoring the pause() call).
        • If you publish your swf using Flash CS3 or CS4 and target Flash Player 9, NetStreams don't reliably dispatch a "NetStream.Buffer.Full" NetStatusEvent for progressive downloads.
        • The Video object's scrollRect won't work properly unless the Video's size is initially set to 320x160
        • If you seek() a NetStream to a position between the last keyframe and the end of the video, a NetStreamEvent with the info code "NetStream.Play.Stop" will be dispatched even if the NetStream is paused.
        • If you seek() a NetStream before it dispatches its first RENDER event, it will completely lose its audio.
        • NetStream only dispatches RENDER events when you publish to Flash Player 10 or later. For Flash Player 9, the only reliable way to know that it has rendered is to wait about 50ms.
        • If you call the Video object's attachNetStream(null) method from within the RENDER event handler on the NetStream that was attached to it, Flash occasionally crashes (you can call it from pretty much anywhere else without a problem).
        • Sometimes a NetStream will dispatch a NetStatusEvent with a code of "NetStream.Play.Start" before the buffer has filled
        • As of Flash Player 11, if you call a NetStream's seek() method on the same frame as when it finishes playback, it causes a flicker. This makes seamless looping...well...not seamless. You must wait a frame before doing the seek().
        • Unlike Loader, URLLoader, and Sound, there are no PROGRESS events dispatched by NetStream. To track its loading progress, you'd need to set up a Timer or ENTER_FRAME handler to keep checking the bytesLoaded and bytesTotal.
        • Even if you listen for the appropriate NetStatusEvent indicating that a NetStream is starting and pause() it immediately, you can often see the video briefly animate before it pauses and you can hear the audio briefly as well.
        • If you seek() to a certain time in a NetStream and then immediately check its "time" property, it is often incorrect (reflects the previous time, not the new one)
        • Sometimes a NetStream will report a "time" that is greater than its duration (which would be impossible of course). When it has finished playing, sometimes it reports a "time" that doesn't match the duration either.
        • Occassionally Flash garbage collects a NetStream that's attached to a Video and playing if two LocalConnections are connected with the same name.
        • There is a bug/inconsistency in Adobe's NetStream class that causes relative URLs to use the swf's location as the base path instead of the HTML page's location like all other loaders. Therefore, it would be wise to use the "base" attribute of the <OBJECT> and <EMBED> tags in the HTML to make sure all relative paths are consistent. See http://kb2.adobe.com/cps/041/tn_04157.html for details.
        • A Sound object's length doesn't reflect its duration until it is completely loaded.
        • If close() is called on a Sound object, it no longer reports its bytesLoaded properly so it cannot be reused effectively.
        • Sometimes a SoundChannel's position reports as being greater than the duration (should be impossible)
        • By default, images and swfs from other domains are loaded with heightened security restrictions that prevent bitmap smoothing, BitmapData captures, and script access in swfs.
        • If you add URLVariables to a URLRequest and set the URLRequest's url to a String that has been modified using any of the String's methods like split(), substr(), etc., in certain versions of the Flash Player (like 10.0.12.36) Flash will omit the "?" that separates the URL from the GET variables, causing invalid addresses.

        FAQ

        1. Where do I get the code?LoaderMax is included in the main AS3 GreenSock download zip - just click the "Download" button at the top right corner of this page.
        2. 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:
          var request:URLRequest = new URLRequest("http://www.yourDomain.com/whatever.php");
          var data:URLVariables = new URLVariables();
          data.exampleSessionId = new Date().getTime();
          data.exampleUserLabel = "label1";
          request.data = data;
          request.method = URLRequestMethod.POST;
          var loader:ImageLoader = new ImageLoader(request, {name:"image1"});
        3. 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 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.
        4. 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)
        5. Why do I have to use different loader types (ImageLoader, XMLLoader, SWFLoader) instead of LoaderMax automatically figuring out the appropriate type based on the file extension in the URL?Actually, LoaderMax has a parse() method that can do exactly that (automatically figure out the appropriate loader type 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 LoaderMax.activate([ImageLoader, SWFLoader]). This extra step may seem annoying, but there are a few reasons LoaderMax doesn't activate all loader types by default:
          • Doing so would force ALL types of loaders to be compiled in your swf so that they're available just in case you need them. Your project may never need an SWFLoader or MP3Loader, etc. but they would still be compiled into your SWF to accommodate "lazy" loading. 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 and it definitely allows the system to be more lightweight and efficient. It could literally reduce the file size requirement by more than 60%.

        6. 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.
        7. Can I make suggestions for improving LoaderMax?Please do! Either in the comments section below or in the forums.
        8. 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.Don't worry - you can get code hinting and strong data typing by using the data classes in the com.greensock.loading.data package, but two of the primary objectives were to keep file size to a minimum and encourage readable code, neither of which could be accomplished very well without using a generic vars object by default. There are quite a few optional special properties for various loaders (SWFLoader recognizes 41!) and regular constructor parameters just wouldn't be feasible. Which one is more readable?:
          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 again, if you want strong typing and code hinting, use data classes in the com.greensock.loading.data package (like LoaderMaxVars, ImageLoaderVars, XMLLoaderVars, etc.) which allow you to define all your vars with a special object.

        9. Can I get the source code for the demos above?Sure, download it here.
        10. Is LoaderMax available in AS2? Will it be?The tweening platform and TransformManager, GreenSock's 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 headed towards extinction.
        11. Will you be posting more examples?Yes.
        12. 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.