Memory Management
One downside to cross-fading the loaded content is that everything has to be in memory at once. This doesn't mean much for this sample controller movie, because it only contains a single button. However, your movie will almost certainly be more involved, and in any case, both external SWFs have to be in memory at once. Depending on how large and how processor-intensive your movies are, this can put a strain on RAM and/or performance. But what if you could get rid of the file you don't need any more?
To see this next exercise in action, add the following line at the end of the enterFrame event handler:
trace("target1: " + target1.getBytesTotal() + " target2: " + target2.getBytesTotal())
This will show you the size of the first SWF and the size of the second SWF and, most importantly, it will show you that both remain in memory before you edit the script. However, you can add a movie unload command to one of the target MovieClips to purge the SWF that is no longer needed.
Add the following to the end of the button handler:
obj1.onEnterFrame = function () {
if (this._alpha <=0 ) {
this.unloadMovie();
delete this.onEnterFrame;
}
}
Because you're swapping your target MovieClips, you always know that obj1 contains the last viewed content and is fading out, and obj2 contains the next SWF in line and is fading in. So, you can add a command that says to unload obj1 when the alpha reaches zero or less.
Lastlyand this is importantyou need to make sure that the MovieClip referenced by obj1 doesn't continue to unload its own content. This would make it impossible to reload the target. So, once the unload instruction is given, delete the event handler preventing further execution. The EnterFrame handler gets recreated every time the next-slide button is pressed, so it will be ready again for the next swap.
Other Options
That's it, you're done. As I mentioned at the start of this article, there are many ways to accomplish this goal. You could take a similar approach with levels, instead of MovieClips, for example. I prefer to use MovieClips because I feel that it gives me more control, and some people think it can be easier to manage variables if you keep everything within one level. Another option would be to create a component that you could use, instead of a button, for instance (no pun intended), that would handle all of this for you with just a quick configuration of some parameters. Finally, you could create a class file that could handle most of this for you that you could keep in a class library for future use.
I hope some of you take these suggestions and run with them. If you create your own version of this utility, send it along. I would love to see what you've done with it. If you have a question you'd like answered, send it to me and I'll try to work it into a future story.