15.7. Determining if an Asset Is Loaded

Problem

You want to know if an asset has completed loading into the Player.

Solution

Use the getBytesLoaded( ) and getBytesTotal( ) methods. Alternatively, define a custom isLoaded property for the Sound and MovieClip classes.

Discussion

There are three kinds of assets that can be loaded into a Flash movie using ActionScript: .swf files, JPEGs, and MP3s. The first two types are loaded into movie clips, and MP3s are loaded into Sound objects. Both the MovieClip and Sound classes have methods named getBytesLoaded( ) and getBytesTotal( ), which you can use to determine whether the asset is loaded. So, no matter which type of asset you are loading, the ActionScript is essentially the same.

The getBytesLoaded( ) method returns the number of bytes that are currently loaded into a movie clip or Sound object, and the getBytesTotal( ) method returns the number of bytes that will be loaded when the asset has been completely received. You know that the asset is completely loaded into the Player once the values returned by the two methods are equal.

Tip

The getBytesLoaded( ) and getBytesTotal( ) methods use uncompressed file sizes and thus are not necessarily accurate measurements of the compressed asset sizes. However, their ratio yields a reasonable estimate of what percentage of the asset has loaded.

There is a caveat when comparing the values returned by getBytesLoaded( ) and getBytesTotal( ). Before an object retrieves the information about the file it ...

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.