Section 12.2. Preloading


12.2. Preloading

Although your .swf loader is only 1 KB, the graphics it loads average around 50 KB. Other projects are bound to contain assets that are significantly larger. You won't notice any delay working with these assets locally, but if you post these files online the load time will likely be a problem. The .swf will load quickly, but external assets might not show up for anywhere from a few seconds to several minutes, depending on the file size and the user's connection speed. Without knowing what's going on, a user may think your project is malfunctioning because it looks like nothing is happening during the load.

To solve this problem, your next project will be to create a preloader for the files. A preloader is a widget that uses ActionScript to check the status of the load process and displays it visually so the user always knows when something is loading. The first step will be to use the Flash ProgressBar component to do the heavy lifting.

12.2.1. Using Preloader Components

To implement a preloader using components, follow these steps:

  1. If you haven't already done so, close the Preview window and close load_movie.fla. You'll come back to that file later.

  2. Create a new Flash document and save it as preload_components.fla in the 12 folder. Change the Stage dimensions to 500 x 375.

  3. Create two new layers, for a total of three. Name the first layer progressBar, the second loader, and the third actions.

  4. Choose Window Components to open the Components panel, shown in Figure 12-2.

    Figure 12-2. The Components panel

  5. Select the loader layer, expand the UI Components menu in the Components panel (by clicking on the small arrow), and drag the Loader component to the Stage. This creates an instance of this component on the Stage and adds the component to your Library.

  6. Using the Properties panel, resize the Loader component instance to 500 x 375 (unlocking the aspect ratio constraint if necessary), position it at (0, 0), and assign it an instance name of myLoader.

  7. Select the progressBar layer, and drag the ProgressBar component to the Stage. Position the instance in the horizontal and vertical center of the Stage. Assign it an instance name of myProgressBar.

The Loader component is a bit like the container clip you created earlier, in the sense that your external content will load into it. It won't do anything here but scale the loaded asset to fit within the component's own bounding box. The ProgressBar component will track the loading progress and display a nice animated bar telling the user how much of the asset has loaded.

To get them to work together, you have to set up the ProgressBar component to monitor the Loader component's progress, and then you have to tell the Loader component what to load:

  1. Select frame 1 of the actions layer and enter the script that follows:

     myLoader.autoLoad = false; myLoader.contentPath = "http://www.flashoutofthebox.com/water.jpg"; myProgressBar.source = myLoader; myLoader.load(); 

    The first line tells the Loader component not to load the asset automatically, and the second line tells the Loader what to load. The third line tells the ProgressBar component to monitor the Loader, and the last line starts the loading process.


    Note: In this step, you're loading a server-based asset (a variant of the water.jpg file with which you've been working), because local assets will load too quickly to give any meaningful feedback. If you don't have an Internet connection at the moment, you can switch the pathname to that of a local file and try this another time. You won't see the progress bar in action, but you will at least see the asset load.

  2. Save and test the movie.

The image loads, and the progress bar displays the load progress nicely. As a quick setup, you've placed the ProgressBar component beneath the Loader, as seen in Figure 12-3. This way, when the asset loads, the bar becomes hidden. It won't always be easy to set up your files this way, though. For example, in the previous project, you were able to move the target movie clip around and still load in new assets. To hide the progress bar in that case, you would have to build a nested movie clip setup with both the target movie clip and the ProgressBar component in a parent movie clip.

Figure 12-3. The layered components


In a moment, you'll learn how to clear a preloader so it doesn't have to be hidden at all. However, there's a more pressing problem. Despite the fact that your preload_components.fla file has no graphics in it, it is now a whopping 32 KB. As broadband is rapidly becoming the norm, that may not sound like much, but small file size increases can really add up. To put this in perspective, this is 32 times the size of your first loader.

As you've read in Chapters 8 and 9, this increased file size is because the components used in this file are large. Others are significantly larger. Components are designed to have common interface and scripting structures. This makes working with many components very convenient, and the more that are used, the less noticeable the file size increases become. However, using one or two can cause an unwanted exponential increase in download time. Writing your own preloader can help.


Note: Don't let the size of some components scare you off, but use them judiciously. In addition to the aforementioned economy of scale introduced when many Macromedia components are used, components also make rapid prototyping much easier. Furthermore, many third-party components are much smaller and can be used as alternatives.

12.2.2. Scripting Your Own Preloader

Your preloader will use text to display the percentage of bytes loaded. Every time 1% of an asset is loaded into your Flash movie, the number in the text field will increment by 1. When the percentage reaches 100%, the asset is fully loaded and displays in the movie. While this isn't the most visually exciting preloader in the world, it does serve the purpose of keeping the user informed and is a good starting point for exploring the visual possibilities of preloaders in your own work.

First, set up the file:

  1. Open the load_movie.fla file in the 12 folder, and save it as my_preloader.fla in the same folder.

  2. You'll need to add only one visual asset to this file: a text box into which you'll put the loading information. Select the Text tool and create a dynamic text element about 200 x 30 pixels in size. (The size does not have to be precise; it just needs to be big enough to accommodate the necessary incoming text.) Place it in the lower-left corner of the Stage, and give it an instance name of info_txt.

  3. Set the text size to 14 point and, to keep file size small, set the font to _sans. (Using device fonts may not be as pretty as using custom fonts, but they don't have to be embedded to work.)

Your Stage should now look like the detail shown in Figure 12-4.

Figure 12-4. The dynamic text element on the Stage set up to receive loading information


Now you can start scripting your preloader:

  1. Select frame 1 of the actions layer and add the following to your script:

     var my_mcl:MovieClipLoader = new MovieClipLoader(); 

    This creates an instance of the MovieClipLoader class and stores it in a variable named my_mcl. The MovieClipLoader class will handle the behind-the-scenes loading and progress reporting for you. All you'll have to do is trap the information it provides, and work it into a state that is meaningful to the user.


    Note: Like the _mc suffix you used previously, the optional _txt and _mcl suffixes help Flash provide useful code hints in the Actions panel. However, using ActionScript 2.0 static typing (as discussed in Chapter 8) effectively eliminates the need to use these suffixes, because the data type declaration gives Flash all the information it needs. For example, the MovieClipLoader data type tells Flash that this is a MovieClipLoader object. Even more important than providing code hints, Flash can now check for certain types of errors and, if you make a mistake, can alert you when you publish your movie. (If you are still unclear on any part of this concept, see the "Data Types" sidebar in Chapter 8 for more information.)In any case, though, using the suffixes has no adverse effect, so until you come up with a variable naming convention that you prefer, you may want to continue with this practice.

    Now it's time to set up a system that will allow the MovieClipLoader object to automatically respond to events that it should respond to, but efficiently ignore unrelated events. This is accomplished by creating an event listener. (Briefly, a listener is a generic ActionScript object whose only job is to listen for events and run code in reaction to them. For a detailed look at listeners, see the "Event Listeners" sidebar.)

  2. Create, in the same script, a listener object that you will later register with the my_mcl MovieClipLoader object used to monitor load progress:

     var my_listener:Object = new Object(); 

  3. Now set up the event handlers. Start with the onLoadProgress event handler to trap the loadProgress event. This event is generated throughout the loading process. In addition to broadcasting the loading movie clip reference that is broadcast at all times (so you can tell one load request from another), this event also broadcasts the total file size of the asset (in bytes), and the total amount loaded (in bytes) at the time the event is broadcast.

    From this, you can display any feedback you like. In this case, you're going to display a percentage (loadedBytes/totalBytes * 100), rounded to the nearest integer. Fortunately, you don't have to write a rounding conditional that checks if the number's decimal value is above .5 or not. The Math object will take care of that for you:

     my_listener.onLoadProgress = function (mc:MovieClip, loadedBytes: Number, totalBytes:Number):Void {   info_txt.text = "  Loading: " + Math.round(loadedBytes/totalBytes * 100) + "%"; }; 


    Note: You may have noticed the use of the plus sign (+) when writing the feedback text. When used with strings (text), the plus sign means concatenate, or join together into a string. Note, too, that a trailing space after the colon is used, but no leading space is used before the percent symbol (%).

    Event Listeners

    Imagine yourself sitting in a busy airport. If you had to carefully parse every bit of information going on around you, a significant amount of focus would be required and your energy would be unnecessarily drained. So, you compensate by training yourself to listen for any broadcast containing your flight number, your destination city, and perhaps the name of your airline. This is a more efficient way of processing the data around you. It allows you to automatically react to useful information, and discard background noise.

    ActionScript can do the same thing using event listeners. A listener is simply a standalone ActionScript object that is instructed to listen for specific events and automatically run code when those events occur. This can be very important in the Flash world.

    For example, what if you had to write code that constantly checked if any keys were pressed? That would be very inefficient. Instead, the Key class can help. The Key class is a built-in class that helps you process user interaction via the keyboard. It broadcasts an onKeyDown event whenever a key is pressed and an onKeyUp event whenever a key is released. You can set up an efficient listener so your code will hear those broadcasts and react. This way, your code responds to known events only when they occur, rather than constantly asking if they have occurred or not.

    Listeners are also very helpful when processing information related to the Internet. When you type in a web address in your browser, you are contacting a server; the server receives your request, and then issues a response.

    This delay between request and response means the calls are asynchronousthat is, the results are not available immediately after the request.

    In the " Scripting Your Own Preloader" project in this chapter, you face this dilemma. However, instead of forcing Flash to pause while waiting for something to download, you can set up a listener to trap the events automatically issued by the MovieClipLoader class. This class broadcasts events when content is being downloaded, when it completes, and when there is an error.

    The listener object can capture these events using an event handler syntax that will probably be familiar to you. In this case, onLoadProgress, onLoadComplete, and onLoadError event handlers can be added to the listener, and it can be put to work by being registered with the MovieClipLoader object you create. Although this example centers on the MovieClipLoader class, this process is the same for any ActionScript object that can work with a listener.

    It is good practice to remove a listener using removeListener() when it is no longer needed. For tutorial simplicity, this was not included in the code examples in this book. However, the supplemental source file, my_preloader_02.fla, shows this practice (as well as additional error checking) in use.

    For many more details on listeners, broadcasters, and the design justification for them, see Colin Moock's ActionScript: The Definitive Guide and Essential ActionScript (both from O'Reilly).


  4. Next, set up the onLoadComplete event handler to trap the loadComplete event generated when loading is complete. You will use this to clear the text field so the load meter will effectively disappear after loading is complete (this same event handler could be used to hide the ProgressBar component in the previous project, if you wanted to set up an event listener for that project, too):

     my_listener.onLoadComplete = function(mc):Void {     info_txt.text = ""; }; 

  5. Finally, set up the onLoadError event handler to trap the loadError event generated if an asset does not load:

     my_listener.onLoadError = function(mc):Void {     info_txt.text = "Error: File did not load."; }; 

  6. Now that you've set up the listener, add it to the MovieClipLoader object:

     my_mcl.addListener (my_listener); 

    That's it for the listener. It took a lot more to explain it than to write it, but it will be worth it. Now you have an efficient mechanism for responding to sporadic events.

  7. All that remains is to actually load the external asset so your listener can react. Replace your existing loadMovie() methods with MovieClipLoader instance methods. Switch the path to the web-based version of the graphic to see the loading in action:

     //place in JPEG button event handler: my_mcl.loadClip ("http://www.flash8projects.com/water.jpg", container); //place in GIF button event handler: my_mcl.loadClip ("http://www.flash8projects.com/star_move.gif", container); //place in PNG button event handler: my_mcl.loadClip ("http://www.flash8projects.com/star_move.png", container); 

  8. Save your work and test your movie. You should now see loading information in the dynamic text field the first time an asset is loaded. To check your work, compare your script with the complete script in my_preloader_01.fla, found in the 12 folder of your working directory.

That's enough scripting for now. As these later chapters become more and more ActionScript-rich, it's a good idea to take a break now and then to let everything sink in.

12.2.3. What's Next?

Keeping your files lean and mean is essential to using Flash effectively on the Web. When developing applications for CD-ROM delivery, as you'll see in Chapter 14, you have a little more flexibility. However, even with the added freedom of not having download times to consider, modularizing your content will still provide worthwhile benefits, such as increased performance and more efficient authoring.

Before continuing, think a bit more about preloaders. Beyond the basic status information offered by standard preloaders, some Flash designers create preloader animations that are entertaining and ease the wait with fun distractions. More ambitious designers integrate preloaders tightly into the design, so the experience appears seamless. Text passages, for example, can be used to parcel out nuggets of information during delays. By the time you're done reading the text, the content you requested has loaded and you're ready to view it.

Try to use the formula in the preloader you scripted to create a clever loading animation. Use the resulting number to set the width of a movie clip, or jump to a corresponding movie clip frame. Let your imagination run wild.

In the next chapter, user interaction reaches a peak. You'll use distance learning as a model to record, store, and submit user responses. You'll learn:

  • How to use templates and components to create a simple quiz

  • How to save text values to the user's machine and retrieve the information later

  • How to submit user input to a server

  • How to use a simple PHP script to email the results



Flash 8(c) Projects for Learning Animation and Interactivity
Flash 8: Projects for Learning Animation and Interactivity (OReilly Digital Studio)
ISBN: 0596102232
EAN: 2147483647
Year: 2006
Pages: 117

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net