18.3. Checking Load Progress

Problem

You want to know how much of the data has loaded.

Solution

Use the LoadVars.getBytesLoaded( ) and LoadVars.getBytesTotal( ) methods. Alternatively, use a progress bar (see Recipe 15.9).

Discussion

The LoadVars class’s getBytesLoaded( ) and getBytesTotal( ) methods work in the same way as the methods of the same name from the MovieClip, Sound, and XML classes. Prior to a request to load external data, both methods return 0. Once Flash determines information about the requested data, getBytesTotal( ) returns the total number of bytes to load. The value of getBytesLoaded( ) changes each time there is load progress. All the data is loaded when getBytesLoaded( ) is equal to getBytesTotal( ), provided they’re not both 0. Typically, you should use a movie clip with an onEnterFrame( ) method or an interval function to monitor the load progress. For example:

myLoadVars = new LoadVars(  );
myLoadVars.load("myText.txt");
myLoadVars.onLoad = function (success) {
  // Process loaded data here
};

function monitorLV (  ) {

  // Get the percentage by multiplying the loaded-to-total bytes ratio by 100.
  var percent = Math.round(myLoadVars.getBytesLoaded(  ) /
                 myLoadVars.getBytesTotal(  ) * 100);

  // If the percentage is not a number (no bytes have loaded), set it to 0.
  percent = (isNaN(percent)) ? 0 : percent;

  // Display the load percentage in the Output window.
  trace(percent);
}

You can use a Progress Bar component to monitor the progress of data loaded with a LoadVars ...

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.