|
||||||
|
||||||
Flash Tutorial - Preload, Control & Communicate Between External SWF Files
145 Intermediate
Flash Compatibility: MX
2004 (Principles and ActionScript are
the same in Flash MX / Flash 5 / Flash 4)
Written by: Rabid Lemming
Length: 11,594 words
Assumed Knowledge: Good knowledge of ActionScript and flash
Level: Easy but a lot to cover
Note: This tutorial has not yet been edited - so that I cannot be sure it is error free or that the instruction are easy to follow. It will be edited soon. Thanks - Site Editor: Phil Schulz.
The aim of the tutorial is to learn how to preload external swf files and control and communicate between them
IMPORTANT NOTE: The examples on this page all have play buttons. This is so that all the swf movies on this page do not all try to start preloading their external swf movies at the same time witch would slow the page loading down. Simply click the play button on each movie to see it working.
Note: I recommend you download each of the flash files for the examples in this tutorial as the explanations can be a little long winded but I couldn't help that as their was no easy way to explain it all with out going into detail. However do read this entire tutorial and don’t be put off by the length of the tutorials as although it’s a lot to read its fairly basic stuff
Have you ever noticed how when you publish your flash movie on-line that sometimes the web page will load and your flash movie wont appear for some time. Then when the flash movie dose appear, the preloader just jumps strait to something like 80% loaded. If you have ever come across this you may have asked your self why your flash movie preloader isn't loading the movie as soon as the pages loads and starting from 0% loaded like its meant to. Surly no one wants to look at a white square that’s shows up on the page until the movie shows up as that’s just ugly. Also many users may think the page is not working and leave before the movie shows up. Well in this tutorial we will cover this issue and how to resolve it. You will also learn how to build an external swf preloader for flash MX and flash MX 2004 using components. I will also examine the idea of loading all the external swf in at the beginning of the movie and why this is perhaps not a brilliant idea. I will also cover many other issues and how to communicate between the main swf and the externally loaded swf. I strongly recommend this tutorial as it will give you a lot of useful information for you to use in the future
Set one: Resolving the preloader problems
The reason for why the preloader doesn't show up until the movie is around 80% already loaded is a common problem many people come across. The most common cause for the problem is components. When you add a component to your movie, by default it has the option to be loaded in the first frame of the movie selected. However you do not want this to happen as the only thing you want to load in the first frame of your movie is the preloader and nothing else. Some people often ask if they can add an image to the preloader part of their movie. This will result in the same problem occurring as when the page loads. It loads everything, normally text first then images, then sound and then extras like the flash movie (web pages always load top right to top left and then down). What you want to happen is to allow the page to load and have your flash move preloaded at the same time. However if you have components and images and/or other things in the first frame trying to load at the same time as well, what happens is that the movie won’t be able show up strait away as the first farm of the movie is trying to load all this stuff. When it dose finally show up then half of the things in the movie like the components that don’t appear or aren't used until later on in the movie, have already been loaded and the movie preloader can jump to 80% loaded because most of the movie content was already loaded in the first frame. So to resolve this problem here are some key thing you must do:
When ever you add a component to the stage (this applies to both flash MX and flash MX 2004)
Things to never do and remember:
The best method for preloading:
Wear ever possible load things like large images, sounds and external movies in only when they are needed externally through action script. Don’t go over the top though. people often try to preload small images and sound clips but unless you are loading lots of small things like this in at the same time then its best to just include them in your main movie unless your really desperate to cut down on file size. The more you can preload into your movie externally the better but no need to go on over kill. A lot of users load text in externally. This is not necessary and often causes more problems than its worth. remember text doesn't take up much file size and to preload it will actually cause more problems than it solves and even slow down your movie as uses don't want to wait for a small bit of text to have to load. So unless you are loading loads and loads of text in i would not bother preloading text. The only things you really need to preload are things like large sound files, large images. Often a really good way to cut down of your movie file size is to not use scenes but to import what would have been another scene as an external movie. This will dramatically cut down file size as you can load the external movie in only when you need it and it will save file size by cutting your large movie up into small parts and only loading the parts you want when you need them. things like small images and sounds you only need to load externally when you are loading lots of them at once. The best method is to firstly look at your movie and try to cut it up into smaller moves and load the smaller movies in only when you need them. THEN you can start looking at loading things like sounds and images externally. Then only load the large images and sounds in externally. This will result in a much better web site and this is how the professionals do it. If however your movie is best as one whole thing and not worth cutting up into smaller parts and the only problem is thing like sounds and images making it larger than it should be. Then you can go strait to loading them in externally and skip cutting your movie up into smaller parts as this in only necessary if you movie it self is larger than it should be and needs cutting up. So in other words if you movie is too large cut it up into smaller parts and load those parts in externally. If it’s not movie that’s too large and only that things like images and sounds are making it large. Then only load the images and sounds in externally and avoid cutting your movie up into parts.
The very best preloading method is to have a preloading movie that external loads your main movie in. so that it your preload your main movie in externally to. This will result in possibly the best and most accurate preloading method. See below on how to preload external swf moves and use the method to preload your movies
Set one: Creating an external swf preloader
This works in Flash MX and Flash MX 2004 from action script 6 to action script 7 version 2. See the Flash MX 2004 version using components below or skip down the page by clicking here

Step two: Setting up movie


Step three: Creating a Progress Bar
The progress bar is the small black bar that expands giving you a visual representation of the percentage of the external movie that is loading. It looks something like this:
Progress Bar.



Note: The Instance Name and Movie Clip Names are different. It is always the Instance Name that is important. Remember that Instance Names are case sensitive and must not start with a number or contain spaces. The Movie Clips name can be anything you want (as long as each Movie Clip has it's own unique name). Instance Names do not need to be unique.
Cross Ref: For detailed information about how to name objects see the tutorial on: ActionScript Syntax
Progress Bar ActionScript
You now have to add some code to the Loading bar Movie Clip. What this does is control the width of the bar. So that as more of the object loads the wider bar becomes. The bars width will match the percentage. If 50% has loaded then the bar will be 50 pixels wide etc.
Cross Reference: The comments below are very brief and if you don't understand how the code works I suggest you look at one of the preloader tutorials where you will find a more in depth explanation as to how preloader work: Preloaders or Advanced Preloaders
// When the Flash Movie loads do the following...
onClipEvent (load) {
// Call the following function
function follow(source, target, percent) {
/* Set the variable vector equal to the percentage of the content being loaded and minus current width of this move clip. */
vector = (source-target);
// Set the desp variable equal to the vector variable times by the percent which is the percentage loaded
desp = (vector*percent);
// Return the amount loaded
return (source-desp);
// Reset the target value
dd.target = 0;
// Close the function
}
// Close the above Clip Event
}
// When this Movie Clip enters the frame (every 1/12th of a sec) do...
onClipEvent (enterFrame) {
// Call the function from above to re sets this Movie Clip's width
this._width = follow(this._width, target, .2);
}
Step four: Creating the Preloader Movie Clip
The Progress Bar that you have just created is part of another Movie Clip which controls all the image preloading and displays the Progress Bar and other info such as the percentage loaded:


// Stop the preloader from automatically running
stop();
// Get the total bytes to be loaded
total_bytes = (this._parent.MyExternallyLoadedSWFMovieHolder.getBytesTotal());
// Get the bytes loaded so far
loaded_bytes = (this._parent.MyExternallyLoadedSWFMovieHolder.getBytesLoaded());
// Work out the difference between the total bytes to load and the bytes loaded so far
remaining_bytes = (total_bytes-loaded_bytes);
// Work out the percentage loaded
percent_done = (int((loaded_bytes/total_bytes)*100));
// Set the target bar percentage loaded
bar.ba.target = (percent_done);
// Display progress of percentage loaded in the text box
DisplayProgress = (Math.round(bar.ba._width))+" % loaded.";
// Check to see if everything has loaded
if (bar.ba._width>99) {
// If everything has loaded move onto the next frame
gotoAndPlay(4);
// If everything hasn't loaded then run this code
} else {
/* If everything has not loaded return to frame 2 and try again. This creates a loop and then runs the code above again. Is how everything updates. The values from last time will have changed as more content will have loaded by now. */
gotoAndPlay(2);
// Close the if-else statement
}
// Tell the external movie to goto and play frame label "Play"
// You can use frame numbers too
_root.MyExternallyLoadedSWFMovieHolder.gotoAndStop("Play");
// Stop on this frame
stop();

The ActionScript Layer should now have three
little a's. The ActionScript
Layer is now finished.
The Text layer



Step five: Creating the Timer Movie Clip
This Movie Clip has a small amount of ActionScript that controls the loading of the first Image. Subsequently images are loaded when the user clicks on one of the buttons.

// This is how we automatically load the swf when the movie loads
loadMovie(_root.MyVariable, _root.MyExternallyLoadedSWFMovieHolder);
// Tell the preloader to preload the first image
_root.preloaderloader.gotoAndPlay(2);
// Stop this Movie Clip now the first image has loaded
stop();
Step six: Placing the Timer on the Main Stage

Step seven: The ActionScript
It is the ActionScript on frame 3 of the Main Stage that controls the bulk of the information that needed to preload the external swf movie.
// Create a Movie Clip to load the swf movie into
this.createEmptyMovieClip("MyExternallyLoadedSWFMovieHolder", 0);
// Create a variable to hold the location of where the external swf movie can be located and the file name
// of the swf movie to be loaded in externally as an externally loaded swf movie
// e.g. the path to the image could be like c:\myFolder\MySWFMovie.swf or http://www.MyWebSite.com/myFolder/MySWFMovie.swf
// or if the swf file is in the same location you can use just the swf file name
var MyVariable = "http://www.YourWebSite.com/MySWFMovie.swf";
// Set the loaded content's location on the stage
MyExternallyLoadedSWFMovieHolder._x = 0;
MyExternallyLoadedSWFMovieHolder._y = 0;
// Stop on this frame
stop();
Step eight: The External SWF Movie
In your external swf move that you want to load in externally you MUST add 2 blank frames at the very beginning on the movie in the first scene to load. In the first frame you mush have a stop command and in the second frame you must add the label: Play This is how to do it if you’re not sure



![]()
That's it you should have this:
Set one: Creating the Flash MX 2004 external swf preloader using the loader component

Set one: Creating the Flash MX 2004 external swf preloader using movie clip
Step one: Communicating between the main time line and externally loaded swf movies
Understanding _lockroot method basic ( I recommend you read the advanced explanation too) Skip this if you only have Flash MX as this only works in Flash MX 2004 Flash Player 7 and above
When you load one flash swf movie into another the first issue is when ever you refer to any thing weather it be a text box, button, component or whatever. You have to tell flash wear the thing you want to refer to is located. Now normally this isn't a problem as you just user the target path for locating the object you want to refer to. However when loading one flash swf movie into another it gets a little more complex but quite simple once you get to grasps with it. To understand it properly and how it works we will use an example to help:
Now when you test this movie it works fine and you should get something like this:
However if you load this movie in as an external swf movie it won't work!
Why you may ask. Well because in the code it uses _root witch refers to the
absolute default level of the movie. As it has been external loaded in as an
external swf it is trying to refer to the base level of the main swf and not
the base level of the swf file that has been loaded in. So basically it’s
looking at the time line of the main swf and not the time line of the external
swf. To fix this add:
this._lockroot = true;
To the swf movie been loaded in or add:
MyLoader.content._lockroot = true;
(MyLoader been instance name of the loader component) to the time line of the
flash movie our loading the swf into. If you are loading the swf into a movie
clip use:
myMovieClipInstanceName._lockroot = true;
myMovieClipInstanceName being the instance name of the movie clip that your
loading the external swf into.
As you can see here in this example it uses the same code and although the movie is been loaded in externally the code still works !
So by setting _lockroot = true; you are telling flash that when ever you use the _root. method for referring to something in an externally loaded swf movie you want flash to refer to the external swf movie time line and not the time line of the main movie as it would do if _lockroot = false; this will only work with _root. So you could have _root.MyMovieClipInstanceName to refer to a movie clip in the externally loaded swf movie and it would work so long as _lockroot was set to true. However if you used: this. or just MyMovieClipInstanceName or even _level0. to refer to the same movie clip you will find it probably won’t work
Understanding _lockroot method advanced
When you load certain version 2 components into a SWF file or into the Loader component, the components may not work correctly. These components include the following: Alert, ComboBox, DateField, Menu, MenuBar, and Window. Use the _lockroot property when calling loadMovie() or loading into the Loader component. If you’re using the Loader component, add the following code:
myLoaderComponent.content._lockroot = true;If you’re using a movie clip with a call to loadMovie() , add the following code:
myMovieClip._lockroot = true;If you don’t set _lockroot to true in the loader movie clip, the loader only has access to its own library, but not the library in the loaded movie clip.
The _lockroot property is supported by Flash Player 7. It specifies what _root refers to when a SWF file is loaded into a movie clip. The _lockroot property is undefined by default. You can set this property within the SWF file that is being loaded or in the handler that is loading the movie clip. For example, suppose you have a document called Games.fla that lets a user choose a game to play, and loads the game (for example, Chess.swf) into the game_mc movie clip. You want to make sure that, if _root is used in Chess.swf, it still refers to _root in Chess.swf after being loaded into Games.swf. If you have access to Chess.fla and publish it to Flash Player 7 or later, you can add this statement to Chess.fla on the main Timeline:
this._lockroot = true;If you don’t have access to Chess.fla (for example, if you are loading Chess.swf from someone else’s site into chess_mc ), you can set its _lockroot property when you load it, as shown below. In this case, Chess.swf can be published for any version of Flash Player, as long as Games.swf is published for Flash Player 7 or later. Place the following ActionScript on the main Timeline:
chess_mc._lockroot = true;When calling loadMovie() , set the MovieClip._lockroot property to true in the loader movie, as shown in the following code. If you don’t set _lockroot to true in the loader movie, the loader has access only to its own library, but not the library in the loaded movie:
myMovieClip._lockroot = true;Step two: Communicating between the main movie and eternally loaded swf movie
If you don't have flash MX 2004 or you don't understand the _lockroot method then the best method for referring to anything in the external swf movie is by using the level it's on and the full target path. Here are a few tricks on how to find out what the target path is for any movie clip, button, component or etc that’s in an externally loaded swf movie. Once you know what the target path is for an object in an external swf movie you then know how to refer to it and control it
When you have created your main movie and you have it loaded in as an external swf movie. In the movie that you use to load your main movie into with. That’s the movie you load your external swf into. Do the following in that flash move:
Other methods of getting the target path:
Method one
If you use: trace(TheInstanceNameOfTheThingYouWant.getInstanceAtDepth()); This should produce an out put message of the instance name of that object and its full target path. Example:
this.createEmptyMovieClip("logo_mc",
1);
trace(this.getInstanceAtDepth(1));
Should give a message in the out put window of: _level0.logo_mc
Be sure that in the publish settings you select the Omit Trace actions option
Method two
If you add a selectable dynamic text box or input box to the stage and give it the same instance name and var name in the Property Inspector like myTextBox. If you then place that text box in the movie clip or external swf or component or in the same location as the object you want to get the target path for or refer to. When you test you movie the text box text will automatically display the full target path of wear ever it is located. You can then use that target path from the text box to then refer to the object you want so long as you take away the text box name from the end of the text that you copy from the text box when testing. For example if when you tested your movie the text box displayed the following:
_level0.textfiles.scrollpaneContact.tmp_mc.form.myTextBox;
Then the location and target path for say a button that you wanted to refer to that was in the same location as the text box would be:
_level0.textfiles.scrollpaneContact.tmp_mc.form.MyButtonInstanceName;
As you can see by copying and pasting the text from the text box when testing and then removing the text box instance name you can add the instance name of the actual object you waned to refer to or get the location of
Understanding the basics of level's and layers:
Ok if you are confused lets try and explain a little more what’s going on. Think of you movie like a sandwich. You have your bottom level and in that level you have layers. The default level is _level0 witch is always the base layer of the main movie. So if you use _level0 in your externally loaded swf movie it will be referring to the main time line of the movie that has loaded the external swf movie into. And not the time line of the externally loaded swf. The same is true for _root. (_level0 and _root are identical and their is no difference between them so use witch ever you like but I personally use _root most of the time when I am not loading one swf into another. If I do have an externally loaded swf been loaded into my main movie then I tend to use _level and full target path method instead unless I have set lockroot to true in witch case its sometimes ok to use _root. See above on the lockroot method for an explanation on what lockroot dose). When you open your flash movie you are automatically in level0 and in that level you have your layers. Now as you will know with layers you can order witch objects appear on top of one and another. the same is true with layers as the default level is 0 you can create or put object in levels above or below level 0 to make the appear above or below (behind) level 0. See the tutorial here on understanding levels and layers:
Cross Ref: FS Commands enables the Flash movie to send JavaScript Commands to the web page or the Browser: FS Commands
Layers are like this:
Level 0 (default level. _root will always refer to this level unless lockroot is used)
Ok now you can load an external swf movie into your main movie and you now know how to refer to objects in either movie. Here are some examples for you to use.
This example shows how to communicated between the main movie and the externally loaded movie
Example: Download
the Flash file Free here Will open
and work in Flash MX and Flash MX 2004
This example shows how to control an externally loaded movie clip that has been loaded into a level
Example: Download
the Flash file Free here Will open
and work in Flash MX and Flash MX 2004
FAQ for loading external swf movies :
Some people want to load all their external swf movies in at the same time at the beginning of their movie to save loading them again later on. This in my option is draft. As if you are loading them all in at the start then it defeats the purpose of loading them in the first place as external movies. This is because if you loaded them all in at the start then you may as well include them as part of the main movie and save your self a lot of time and hassle. It’s ok to load several external movies in at once but try to avoid it if you can as you’re save your self a lot of problems and hassle. If you really must preload all or some of your external swf movies in at the same time see below on how to do this. This is based on the very first example at the top of this page but there are some difference in the code. I recommend you download the flash file though as the explanation is a little long winded but I couldn't help that as no easy way to explain it all.
IMPORTANT NOTE: Name all the external swf movies like so: 0.swf, 1.swf, 2.swf, 3.swf and ect... (Always start from 0)
Multiple External SWF Movie Loader :
This works in Flash MX and Flash MX 2004 from action script 6 to action script 7 version 2.
IMPORTANT NOTE: If you know how many externals swf movies you are loading and that number will never change then you can use the one of the following sets of code :
For loading 1 external swf movie:
this.total_bytes = (_root["MyExternallyLoadedSWFMovieHolder"+0].getBytesTotal());
this.loaded_bytes = (_root["MyExternallyLoadedSWFMovieHolder"+0].getBytesLoaded());
For loading 2 external swf movies: