15.8. Getting the Percentage of an Asset That Has Loaded
Problem
You want to determine what percentage of an asset has loaded.
Solution
Use the getBytesLoaded( ) and
getBytesTotal( ) methods. Alternatively,
you can create a custom
percentLoaded property for the
Sound and MovieClip
classes.
Discussion
You can use the getBytesLoaded( ) and
getBytesTotal( ) methods to determine the
percentage of an asset that has loaded. The percentage is calculated
by determining the ratio of the bytes loaded to the total bytes:
ratio = myObj.getBytesLoaded() / myObj.getBytesTotal( );
The ratio is always between 0 and 1. Therefore, to format the percentage for display, you can multiply the ratio by 100. If you want the percentage to be a whole number, you can round the result as well:
percentLoaded = Math.round(ratio * 100);
The only caveat is that before any information about the asset has
been retrieved (such as its file size), the getBytesLoaded(
) and getBytesTotal( ) methods both
return 0, and 0 divided by 0 does not yield a valid number.
Therefore, you should also use the isNaN( ) (is
Not-a-Number) function to catch if the percentage is not a valid
number and set it to 0 instead:
if (isNaN(percentLoaded)) {
percentLoaded = 0;
}You can encapsulate this process by defining a custom
percentLoaded property for the
Sound and MovieClip
classes. The following code should be added to the
Sound.as file created in Chapter 13:
// The getPercentLoaded( ) method returns the percent that has loaded as a whole // ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access