PreloadAssetManager – An Intelligent Preloading Queue
- Compatibility: Flash Player 6 and later (ActionScript 2.0) (FLV preloading requires Flash Player 7)
- File Size added to published SWF: About 3Kb
|
|
|
Join Club GreenSock to get updates and a lot more
NOTE: PreloadAssetManager has been sunset and is no longer actively enhanced or supported. Feel free to use it if you want, though.
DESCRIPTION
Provides an easy way to invisibly preload SWFs, FLVs, or images and optionally trigger a callback function when preloading has finished. It also provides _width and _height information for all successfully preloaded SWFs or images, and duration information for FLVs (assuming they were encoded properly and have MetaData). By default, it will initially only load enough of each asset to determine the size (bytes) of each asset so that it can accurately report the percentLoaded_num, getBytesLoaded() and getBytesTotal(), then it loops back through from the beginning and finishes all the preloading. If you're not going to use a preloader status bar that polls these methods/properties, you can just set the trackProgress_boolean property to false to skip that initial delay.
OBJECTIVES
- Provide an easy way to sequentially preload assets.
- Determine the _width and _height of any preloaded SWFs or image assets as well as the duration of any FLV assets.
- For easy status reporting, provide percentLoaded_num, getBytesLoaded() and getBytesTotal() information for the entire group of assets in any PreloadAssetManager instance.
- Allow for any asset to be prioritized in the loading queue at any time (for example, if the user clicks on something that requires an asset that hasn't loaded yet).
- Allow the entire queue to be paused and resumed at any time (if, for example, you need to perform some other bandwidth-intensive action)
- Build in the ability to call any function when either a particular asset has finished preloading or when a group of assets have finished preloading and allow the developer to pass any number of arguments/parameters to that function.
- If an asset cannot be loaded, implement a timeout procedure so things don't get hung up indefinitely.
USAGE
- Description: Constructor. If you pass in an assetUrls_array, it will automatically call the start() function and begin preloading. You can pause() if you want.
- Arguments:
- assetUrls_array: [optional] An array of urls that should be preloaded
- onComplete_func: [optional] A reference to a function that you'd like to call as soon as all of the assets in this PreloadAssetManager instance have been preloaded.
- onCompleteArguments_array: [optional] An array of arguments to pass the onComplete_func function.
- trackProgress_boolean: [optional] true by default. If you're NOT going to use a preloader status bar that polls the precentLoaded_num, getBytesLoaded() or getBytesTotal(), set this value to false to skip that initial delay and speed things up.
- Description: Adds an asset to the PreloadAssetManager's queue.
- Arguments:
- url_str: The url of the asset that needs to be preloaded
- onComplete_func: [optional] A reference to a function that you'd like to call as soon as this asset has been preloaded.
- onCompleteArguments_array: [optional] An array of argument values to pass the onComplete_func function.
- Description: Adds an asset to the PreloadAssetManager's queue.
- Arguments:
- assetUrls_array: An array of URLs that need to be preloaded
- onComplete_func: [optional] A reference to a function that you'd like to call as soon as all of the assets in this PreloadAssetManager have been preloaded.
- onCompleteArguments_array: [optional] An array of argument values to pass the onComplete_func function.
- start_boolean: [optional] false by default. If true, the PreloadAssetManager will be forced to start preloading as soon as these assets have been added.
- Description: Starts preloading the assets (same as resume() if things are paused).
- Description: Resumes all preloading.
- Description: Pauses preloading in ALL PreloadAssetManagers.
- Description: A STATIC method that allows you to prioritize a particular asset (bump it up to the top of the queue). You can also use the non-static prioritizeAsset() method or the PreloadAsset.prioritize() method to perform a similar action.
- Arguments:
- url_str: The URL of the asset that should be prioritized.
- Description: A STATIC method that allows you to find the PreloadAsset instance with a particular URL. This is useful if you want to find the _width or _height or duration of an asset but only know the URL.
- Arguments:
- url_str: The URL of the asset you'd like to find.
EXAMPLES
-
import gs.dataTransfer.PreloadAssetManager;
-
var preloader_obj = new PreloadAssetManager(["myFile1.swf","myFile2.swf"], onFinish);
-
function onFinish(pl_obj:PreloadAssetManager):Void {
-
trace("Finished preloading all " + pl_obj.assets_array.length + " assets!");
-
var a = pl_obj.assets_array;
-
for (var i = 0; i <a.length; i++) {
-
if (a[i].fileType_str == "flv") {
-
trace("--Asset: "+a[i].url_str+" had a duration of: "+a[i].duration);
-
} else {
-
trace("--Asset: "+a[i].url_str+" had a width of: "+a[i]._width+", and a height of "+a[i]._height);
-
}
-
}
-
}
-
import gs.dataTransfer.PreloadAssetManager;
-
import gs.dataTransfer.PreloadAsset;
-
var preloader_obj = new PreloadAssetManager();
-
var pl1_obj = preloader_obj.addAsset("myFile1.swf", onPreload);
-
var pl2_obj = preloader_obj.addAsset("myFile2.swf", onPreload);
-
preloader_obj.start();
-
function onPreload(pl_obj:PreloadAsset):Void {
-
trace("finished preloading: "+pl_obj.url_str+", _width: "+pl_obj._width+", _height: "+pl_obj._height);
-
}
preloader progress bars) like so:
-
import gs.dataTransfer.PreloadAssetManager;
-
var preloader_obj = new PreloadAssetManager(["myFile1.swf","myFile2.swf"]);
-
this.onEnterFrame = function() {
-
myPreloader_mc.bar_mc._xscale = preloader_obj.percentLoaded_num;
-
if (preloader_obj.percentLoaded_num == 100) {
-
gotoAndPlay("start");
-
}
-
}
Need Help?
Feel free to e-mail me a question. Or post your question on the new forums. I'd highly recommend joining Club GreenSock to get prioritized access to my time in answering your question, and so that you receive updates and lots more. When you e-mail your question, please include a simplified FLA file (and any class files) that clearly demonstrates the problem and provide a brief explanation.
Copyright 2008, GreenSock, Inc.
"NO CHARGE" NON-EXCLUSIVE SOFTWARE LICENSE AGREEMENT
-----------------------------------------------------------------------------
PLAIN ENGLISH SUMMARY:
- You may use the code at no charge in 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. It doesn’t matter if you are paid to create the site/product. If you charge end users a fee, you must sign up for a corporate Club GreenSock membership which comes with a commercial license granting you permission to do so. See http://blog.greensock.com/club/ for details.
- Since the code is updated frequently and developers are best served by having the latest version, please avoid (or at least minimize) distributing the source code outside your organization.
- Use at your own risk. I offer no warranties.
- Please respect the copyright.
-----------------------------------------------------------------------------
LEGALESE:
This is a legal agreement between you (either an individual or a single entity) and GreenSock, Inc. ("GREENSOCK") for the proprietary GreenSock ActionScript code known as TweenLite, TweenFilterLite, TweenMax, TweenGroup, OverwriteManager, and other code that is freely available for download at http://blog.greensock.com or http://www.greensock.com (this code and documentation, as well as any updates which may at GREENSOCK's sole discretion be provided to you from time to time, are referred to in this Agreement as "PROGRAM") By installing, copying, or otherwise using the PROGRAM, you agree to the terms and conditions of this Agreement. If you do not agree to the terms and conditions of this Agreement, please do not install or use the PROGRAM.
I. LICENSE
A. Subject to the terms and conditions of this Agreement, GREENSOCK hereby grants you a non-exclusive, worldwide, non-transferable right to use the PROGRAM in web sites, games, applications, components and other software for which the end user is NOT charged any fees. If you would like to use the code in a commercially licensed software product for which end users are charged a fee (either for usage or access), simply sign up for a corporate Club GreenSock membership at http://blog.greensock.com/club/.
II. LIMITATION OF LICENSE AND RESTRICTIONS
A. You agree that you will not disclose, sell, rent, license, or otherwise distribute the PROGRAM's source code or any derivative works thereof to any third party without the prior written consent of GREENSOCK. Derivative works are defined as modifications that add substantive functionality to the PROGRAM and do not include bug fixes or other minor modifications required to operate the PROGRAM as originally intended. Limited distribution of the source code to vendors as part of your Work Product is acceptable so long as they agree to the terms of this Agreement. You agree not to modify or delete GreenSock's existing copyright notice located in the source code.
B. You may use, duplicate, and distribute the compiled object code solely as embedded in a Work Product created by you, either for your own use or for distribution to a third party so long as end users of the Work Product are not charged a fee for usage. Please see http://blog.greensock.com/licensing/ for descriptions of Work Products that qualify for the "No Charge" license.
III. CONSIDERATION
A. The license rights granted to you under this Agreement are at no charge, but only in the following circumstances: If, either on your own behalf or on behalf of a third party, you incorporate the Software into a web site, software application, program or any component thereof (collectively, “Work Productâ€), which in the case of a web site, must be accessible to internet users without payment of a fee of any kind by a user, and in the case of a software application, program or component, neither you nor anyone to whom you distribute the Work Product charges a user a fee of any kind to use such Work Product or application, program or component into which such Work Product is embedded. The foregoing shall apply regardless of whether you are paid to create such Work Product and, under any circumstances, shall be subject to the prohibition against distribution of Source Code set forth in Section II.
B. In the event your intended use of the Software does not meet the criteria for the “no charge†license rights set forth in the immediately preceding paragraph, then you are not licensed to use the PROGRAM under this Agreement and must license the PROGRAM under GreenSock’s separate fee-based Software License Agreement which is granted to corporate Club GreenSock members (see http://blog.greensock.com/club/ for details).
IV. TITLE AND OWNERSHIP
A. The PROGRAM is licensed, not sold, and is protected by copyright laws and international treaty provisions. You acknowledge that no title to the intellectual property in the Software is transferred to you. You further acknowledge that title and full ownership rights to the PROGRAM, including all intellectual property rights therein, will remain the exclusive property of GreenSock and you will not acquire any rights to the PROGRAM except as expressly set forth in this Agreement. You agree that any copies of the PROGRAM you make will contain the same proprietary notices which appear on and in the PROGRAM.
V. DISCLAIMER OF WARRANTY AND LIMITATION OF LIABILITY
A. THE PROGRAM IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. GREENSOCK DOES NOT WARRANT THAT THE FUNCTIONS CONTAINED IN THE PROGRAM WILL MEET YOUR REQUIREMENTS OR THAT OPERATION WILL BE UNINTERRUPTED OR ERROR FREE. GREENSOCK shall not be liable for special, indirect, incidental, or consequential damages with respect to any claim on account of or arising from this Agreement or use of the PROGRAM, even if GREENSOCK has been or is hereafter advised of the possibility of such damages. Because some states do not allow certain exclusions or limitations on implied warranties or of liability for consequential or incidental damages, the above exclusions may not apply to you. In no event, however, will GREENSOCK be liable to you, under any theory of recovery, in an amount in excess of the license fee paid by you under this Agreement. Notwithstanding anything else in this agreement, you agree to indemnify GREENSOCK, its assignees, and licensees, and hold each of them harmless from and against any and all claims, demands, losses, damages, liabilities, costs, and expenses, including legal fees.
B. GREENSOCK may, at its sole discretion, provide support services related to the PROGRAM, but has no obligation to do so.
VI. TERMINATION
GreenSock may terminate this Agreement at any time if you fail to comply with the terms and conditions of this Agreement.
VII. MISCELLANEOUS
A. This Agreement shall be construed in accordance with the laws of the State of Illinois. Should you for any reason bring a claim, demand, or other action against GREENSOCK, its agents or employees, arising out of this Agreement or the PROGRAM licensed herein, you agree to bring said claim only in the Illinois Court of Claims.
B. THIS AGREEMENT REPRESENTS THE COMPLETE AND EXCLUSIVE STATEMENT OF THE AGREEMENT BETWEEN GREENSOCK AND YOU AND SUPERSEDES ALL PRIOR AGREEMENTS, PROPOSALS, REPRESENTATIONS AND OTHER COMMUNICATIONS, VERBAL OR WRITTEN, BETWEEN THEM WITH RESPECT TO USE OF THE PROGRAM. THIS AGREEMENT MAY BE MODIFIED ONLY WITH THE MUTUAL WRITTEN APPROVAL OF AUTHORIZED REPRESENTATIVES OF THE PARTIES.
C. The terms and conditions of this Agreement shall prevail notwithstanding any different, conflicting, or additional terms or conditions which may appear in any purchase order or other document submitted by you. You agree that such additional or inconsistent terms are deemed rejected by GREENSOCK.
D. GREENSOCK and you agree that any xerographically or electronically reproduced copy of this Agreement shall have the same legal force and effect as any copy bearing original signatures of the parties.
| I'd like to donate & get bonus classes, update notifications, SVN access, and more. |
on February 7th, 2007 at 8:42 am
Great Class!
How do I resolve the scope in an onFinish function?
coverMC = target.createEmptyMovieClip(”cover”,target.getNextHighestDepth());
var preload_obj = new PreloadAsset(coverImage, onFinish);
function onFinish(asset_obj:PreloadAsset):Void {
trace(”Finished preloading: “+ asset_obj.url_str+” and its width is: “+asset_obj._width+” and its _height is: “+asset_obj._height);
trace(this);
// here I want to load in coverMC
}
how do I load the preloadAsset into coverMC when onFinish is called?
on February 7th, 2007 at 4:53 pm
If you want to control the scope of the onFinish call, I’d recommend using the mx.utils.Delegate class that comes with Flash. Then to load your asset into coverMC, you could use something like loadMovie() So your edited code would be:
import mx.utils.Delegate;
coverMC = target.createEmptyMovieClip(â€coverâ€,target.getNextHighestDepth());
var preload_obj = new PreloadAsset(coverImage, Delegate.create(this, onFinish));
function onFinish(asset_obj:PreloadAsset):Void {
trace(â€Finished preloading: “+ asset_obj.url_str+†and its width is: “+asset_obj._width+†and its _height is: “+asset_obj._height);
trace(this);
coverMC.loadMovie(asset_obj.url_str);
}
on April 4th, 2007 at 9:59 am
Preloading works super fine! Thank you very much for this class.
I am preloading a bunch of FLVs. Once they get at 100%, how do I access them using a NetStream object (or other) ?
(I need to implement something that initates the playback of the first one, when it reaches the end I must start the second one, so on…)
on April 4th, 2007 at 10:41 am
Leolea, this class simply preloads your assets into your browser’s cache; it is not meant to be used to play back and manage your FLVs once they’re preloaded. There’s nothing special that you need to do in order to access the preloaded FLVs – just call them as you normally would either using a NetStream object of your own or an FLVPlayback component or whatever. The user’s browser will be smart enough to used the cached versions instead of going out to the web and downloading them again.
on April 25th, 2007 at 11:43 am
Hmmm. A little customization might be necessary for streaming FLV handling. An ideal FLV preloader might wait until the currently-streaming FLV is fully cached before loading an FLV in the background.
If the user requests a new FLV, it would ideally halt the bg-downloading stream and resume it after the requested FLV was fully cached. That assumes it’s possible to halt (and resume) a stream?
If the user requests the background-loading FLV, it’d need to be swapped into the playback area without re-starting that netstream from the beginning.
Has anyone out there tried something like this?
on April 25th, 2007 at 11:59 am
Gabriel, the issues you bring up are exactly why I built this class. It’s very easy to pause preloading and resume it anytime you want (see the pause() and resume() functions) so that you can manage the user’s bandwidth efficiently. You can also prioritize any asset anytime based on what the user clicks on. So if asset #2 is currently preloading, but the user clicks on something that requires asset #6 (which hasn’t been preloaded yet), you can prioritize it immediately (see the prioritize() function).
on April 25th, 2007 at 3:11 pm
I definately like thought of being able to prioritize, pause and resume the loading of assets.
After a little investigating, it seems like Flash can’t resume downloading a half-cached FLV? It just starts the stream over from scratch. This can make pausing and resuming the queue a frustrating experience–if the currently-playing clip ends before the preloading clip is finished, the preloading clip is flushed and then starts loading again from the beginning.
It’s not a flaw in your preloader, so much as it is a difficulty with FLV caching. Ideally, we should be able to pause the video stream itself (pause buffering), then resume it later (resume buffering). If we could drop the currently-preloading clip into the video object without re-starting the stream (allowing it continue buffering from where it is), but still start playing from the beginning, we’d be set.
on August 10th, 2007 at 5:02 pm
Hi! This class has made my life much easier… I have a couple of questions, though:
1. Is there a way to get the width/height of the FLV, alongside the duration?
2. Do you anticipate adding an XML option to this class? For example, the ability to load ANY kind of file… images, xml, swfs, flvs, etc.
Thanks, great job!
-nick
on August 14th, 2007 at 12:32 am
Nicolas, I just added the ability for the width, height, videodatarate, framerate, audiodatarate, and basically all of the available meta data in an FLV to be read in when it preloads. The sample is updated too. Keep in mind that not all FLVs have this meta data available – it depends on the software you used to encode the FLV. Sorenson Squeeze seems to do a good job, but several other software packages omit most of the meta data in which case this class obviously won’t be able to grab it.
Enjoy!
on September 25th, 2007 at 10:17 pm
Great class.
Implemented it in a project we just did requiring preloading a number of FLVs (user has to disconnect their internet connection in the middle of a set of videos). Worked like a charm.
Thanks.
on October 5th, 2007 at 4:35 pm
Is there a way to destroy the PreloadAssetManager object or will simply deleting the var kill any preloads that may currently exist?
Thank you!
on October 5th, 2007 at 4:46 pm
Krom, you can call the destroy() method on your PreloadAssetManager instance. Or if you want to pause ALL preloading that’s being handled by any/all PreloadAssetManagers, just call the static PreloadAssetManager.pauseAll() method.
on October 29th, 2007 at 3:55 pm
Please keep in mind that PreloadAssetManager is meant to preload assets, not buffer video. So if you have a 10 minute FLV and want to buffer 2 minutes of it before playing it, use a NetStream and its bufferTime property instead of PreloadAssetManager. My class simply leverages the browser’s cache to do its magic, but in order to work properly, it needs to fully download an asset. If you download 20% of an FLV using PreloadAssetManager and then try to play that on the screen, Flash will request the file from the browser which will in turn check its cache and since it’s not fully there, it’ll make the request from the server and start the load over again. Not ideal by any means.
on November 7th, 2007 at 4:01 pm
Very useful.
Is there any way to get the percentLoaded_num of an individual asset?
I want to build separate progress bars for each asset.
on November 7th, 2007 at 4:26 pm
Mark,
You can check the progress of any asset after you’ve added it to the PreloadAssetManager. For example, to check the status of a file named “myURL.swf”, do something like:
var asset_obj = PreloadAssetManager.getAsset(”myURL.swf”);
var percentLoaded_num = (asset_obj.getBytesLoaded() / asset_obj.getBytesTotal()) * 100;
on December 4th, 2007 at 2:53 pm
I’m just now starting to learn some of the more advanced functions of actionscript and I’m pretty sure that I’ve got the hang of this class but I have a question that will hopefully clear some things up for me.
Say I’ve got a movieclip that loads a random jpg from a list as a “background” so, in order to make sure that the background comes up without a hitch, I have to have all of the backgrounds loaded. My question is whether or not I should use loadMovie to get the jpg into the movieclip or some other function now that the jpg has already been preloaded. Also, should I be referring to the PreloadAssetManager’s array_asset for the src of the image now or just stick with the original url?
I may just be missing something but, I’ll preload the backgrounds and when I go to load the image, I notice in the bandwidth profiler that the swf has requested the file again even though the file should be cached.
Whatever help you can provide would be greatly appreciated.
on December 4th, 2007 at 3:04 pm
Yes, you’ve got it right, Stephen – you need to use loadMovie() (or its equivalent) to load your background images into place. PreloadAssetManager is ONLY meant to get the assets into your browser’s cache, nothing more. And that also explains why Flash’s bandwidth profiler is requesting the file again. That’s to be expected, and that’s exactly what the browser does too, but since it checks its cache FIRST before hitting the server again, it finds the asset(s) and loads them from there for much snappier performance. Again, PreloadAssetManager leverages the BROWSER’S cache but Flash’s bandwidth profiler doesn’t.
on January 3rd, 2008 at 6:03 pm
Thank Goodness.
Spent the whole day looking for a sollution. This one works.
YOU ROCK!
on January 26th, 2008 at 11:29 am
awesome, i was starting to implement a simple version of this and happened across yours, does everything i want and does it very well :) will be sure to let you know of the project url when it’s done! thank you for saving my time :)
on January 28th, 2008 at 5:30 pm
Hi,
I would like to know if this preloading asset exist for AS3 ?
if it doesn’t, will u think about converting this asset for AS3 ?
Thanks for ur time if you could answer on my email. it would be great.
on January 30th, 2008 at 11:47 am
I’ll probably port this to AS3 when I get a project that requires it. I’m not entirely sure when that’ll be though.
on March 11th, 2008 at 10:48 am
Jack, thanks for the code. I got it to work (took a while because I’m novice and never worked with custom classes before). I’ll be spreading the good word about your blog and generous sharing. Thanks again.
on April 7th, 2008 at 3:45 pm
Buddy you are a genius. This is by far the best preloader I’ve come across.
on May 9th, 2008 at 7:36 pm
Hi,
RE AS3 integration.
I guess we can use this on a preload page to cache as3 assets.
ie
preload.html
_as2 preload assets (AS3.swfs)
_onComplete ( getURL( “next.html” )
next.html
_AS3 assets
yes?
Thanks i love this class. I train my students to use it in managing their flash frameworks.
Oyster
on January 25th, 2009 at 1:37 pm
for some who were looking for a AS3 solution, I just found this
http://code.google.com/p/bulk-loader/
it looks pretty good, I have not dug into it seriously yet.
Hope you do not mind me posting an alternative Jack, but it seemed from your comments that you were not likely to be doing an AS3 solution anytime soon.