SoFunction
Updated on 2025-04-11

Perfect loading implementation method

Reading out-of-town data to participate in Flash application deployment is a very important and common task, especially we often need to detect the progress of this data loading. The MovieClipLoader (hereinafter referred to as MCL) class has greatly simplified this troublesome work. In addition, it allows us to obtain more needs and reduce the amount of code. We can use a separate MovieClip class to load one, or multiple out-of-land resources to the specified MC or hierarchy, or we can formulate different MCL instances for each loading work.
I decided to complete this tutorial in two parts. First, we will introduce the basic usage of MCL; then we will introduce how to use a separate MCL instance to read out-of-town resources to different MCs, and we will join the listener object to participate in the work. Of course, tasks can be completed without a listener. We will not introduce listeners for the time being, because this will make it easier for you to understand MCL.
So, let’s first understand what callback functions are available in MCL, and there will be a detailed introduction later (aw attached: My personal understanding of callback functions is a method that determines a certain class group and parameters in advance, and has specified functions). Here you can understand what a callback function is):
The callback function of the MovieClipLoader object:
Event callback functions (when strictly requiring data types, they are not methods, Houxiang):
* ()- -Flashed when loading begins
* ()-  Triggered during read progress
* ()- -Triggered after the first frame after the read resource is loaded
* ()-Freezes when the read foreign resource has been completely downloaded to the local area.
* ()-Free when an error occurs when loading a foreign resource.
* ()- Remove or terminate a loaded foreign resource.
Method callback function:
* (target:Object):Object - Reading progress of foreign resources, the parameters are MC objects (aw appendix: In fact, MC data type is also an object). Returns an object that contains two pre-determined properties (Houxiang)
To understand these callback functions well, it is the best way to try it out. Of course, MCL is only available after Flash7, so don’t forget to release it as a version number of 7+ when it is released. If you use FlashPlayer directly to debug, you may encounter some problems. We recommend debugging in the browser (personal opinion: For situations where it is difficult to obtain foreign resources, such as the Education Network obtains public network resources, it is best not to debug in the IDE)
In our example, we will use an MCL object to read different pictures and place them into different empty MCs. The swf file and image source file to be used in this example will be found (personal suggestions: Actually, it is not necessary to see whether the source file should be used after reading this article)
==========
1. Create a new Flash document and enter the following script in frame 1:
_root. ="on";
function myTrace(msg)
{
_root. += msg + newline;
_root. = _root.;
}
Here we are establishing a tracking debugging mechanism, and the debugging (variables) will be output to the text box component. The method "myTrace" here is a predefined function, which helps us successfully monitor certain information; the second sentence is to enable the text box to output the latest monitoring value at any time.
2. Now pull a TextArea component from the assembly library into the scene, and give it the appropriate size, as well as an instance name traceBox (corresponding to the script above)
3. Next, we need to build a new MC component. And deploy 3 instances on the scene, name them myMC1, myMC2, and myMC3 respectively. We will load the pictures or swf videos into them and adjust their size as needed after they are downloaded locally. In fact, artificially changing the size of the picture will cause many bad consequences, such as the generation of jagged teeth, but in order to let everyone understand the use of the onLoadInit event, we will do this.
4. Then, we create an MCL object and enter the following script in the first frame:
var myMCL = new MovieClipLoader();//create an instance of MovieClipLoader
aw appendix: Here I want to translate Rosso below, about Object. Because in the comments of the above code, foreigners use the word instance. In literal translation, Object is "object"; Instance represents "instance". The former focuses more on its data type, while the latter focuses more on its objective existence.
5. Now we can deploy the script, in the first frame:
 = function (targetMC)
{
var loadProgress = (targetMC);
myTrace ("The movieclip " + targetMC + " has started loading");
myTrace("Bytes loaded at start=" + );
myTrace("Total bytes loaded at start=" + );
}
The first line of this function declares a (object type) variable. Obviously, the value of this variable is obtained by the getProgress method of the myMCL object. I have just introduced the getProgress method. Here you can see that the returned is the bytesLoaded property of the loadProgress object.
Here I am talking about something: Why do I return an object instead of a specific value? There is a reason for this. The function returns the value function to make the programming more perfect, however, in many cases, we are not returning a value, we may return two or more values, and even their data types are different. In this way, only return through the form of an object. This is the easiest and most efficient way to solve the problem. The following three sentences myTrace echo the monitoring function we defined before, so that we can see the variables we are concerned about.
6. We have deployed the corresponding work for the onLoadStart event, and next we will deploy the work for the above other events. Next is onLoadProgress, which accepts three parameters: targetMC, loadedBytes, totalBytes. Represents the target container MC instances respectively; the volume and total volume that have been read.
 = function (targetMC, loadedBytes, totalBytes) {
myTrace ("movie clip: " + targetMC);
myTrace("Bytes loaded at progress callback=" + loadedBytes);
myTrace("Bytes total at progress callback=" + totalBytes);
}
7. Our onLoadComplete method only accepts one parameter, which is the container MC instance. Like onLoadStart, we use the getProgress method to return the read situation.
 = function (targetMC)
{
var loadProgress = (targetMC);
myTrace (targetMC + " has finished loading.");
myTrace("Bytes loaded at end=" + );
myTrace("Bytes total at end=" + );
}
8. The onLoadInit method will start execution after all loaded content is downloaded into the local container MC. This will allow you to better control the properties of the content loaded in. The picture I chose was very large so that we could see the reading process more clearly, and I also had to trim the size of the picture that had been loaded so that it could be displayed all.
 = function (targetMC)
{
myTrace ("Movie clip:" + targetMC + " is now initialized");
targetMC._width = 170;
targetMC._height = 170;
}
9. There is also a callback method onLoadError. If an error occurs, it will be triggered. As an excellent programmer, avoiding errors is essential when deploying a complete application!
 = function (targetMC, errorCode)
{
myTrace ("ERRORCODE:" + errorCode);
myTrace (targetMC + "Failed to load its content");
}
10. Well that's the hard work out of the way. Now we just have to load the files in to their respective targets, using loadClip, and passing it two arguments: the location of your file, and the destination movieclip for the file to load in to.
10. We have finally deployed the most complex work. Next, we just use the loadClip method to read what we need. The two parameters of the loadClip method are the address of the foreign resource and the instance of the container MC.
("/","_root.myMC1");
("/ ", "_root.myMC2");
("/", "_level0.myMC3");
The path can be selected as a relative path. Note that the relativeity of paths is also a big problem. When SWF is referenced in HTML that is not the current path, follow the path where the HTML is located! This is something that many Flash tutorials ignore. So, sometimes absolute paths also have the benefits of absolute paths. [Download the path problem source file, it will be clear at a glance after downloading]
All debugging is best done in the browser, not in the IDE. And the script output method must be AS2.
Remember, for everything to work properly you need to be testing throuhg a browser (and preferably on line so you can see the files loading in real time). You also need to be exporting your code as ActionScript 2.
In the second part of this tutorial I'm going to show you how to use the MovieClipLoader class in a real-world situation, in order to solve a common problem when assigning event handlers to MovieClips dynamically.
Next, I will introduce the situation of calling MCL in real time. In order to adapt to more applications, we often make dynamic work for MCL.
aw voice-over: Sometimes, we write this:
1、var mcl:MovieClipLoader = new MovieClipLoader ();
2、var mcl = new MovieClipLoader ();
It was found that the first writing method could not be used to formulate event methods such as onLoadStart for MCL. This is a problem arising from the compiler based on the data type of the specified variable. Some friends of osflash have given some useful opinions, and I also found that this issue involves the incident response mechanism within Flash. I might as well introduce it:
Three incident response mechanisms of Flash
=====
1. Simple callback function, the oldest;
2. Listener, ASBroadcaster, FlashMX era;
3. Event listener, EventDispather, FlashMX2004 era
Here, MCL uses the second mechanism, while the entire V2 component uses the last mechanism.
Attachment: MCL official statement, note: The above methods only include the getProgress method!
intrinsic class MovieClipLoader
{
function MovieClipLoader();
function addListener(listener:Object):Boolean;
function getProgress(target:Object):Object;
function loadClip(url:String, target:Object):Boolean;
function removeListener(listener:Object):Boolean;
function unloadClip(target:Object):Boolean;
}
Personally, I believe that 1 and 2 can be used when data types are not strictly required.
The following is a way to use a listener to detect MCL events. Before this, we solved one of the most common problems, and we often see someone asking questions in forums like this:
Quote
Hello everyone, I dynamically built some MCs and assigned them one by one an event handle (flag) to them. Then I read out of the land resources into them. But these assigned event handles are no longer working!
Immediately afterwards, the questioner will usually post a pair of messy codes and shout for help.
So, let’s first analyze the reason for this error: when the foreign resource is loaded into an MC, the MC will be re-initialized. This means that any pre-made code will be wasted. There is no relevant trouble for developers to arrange MCs manually on the stage, because any code that is directly formulated to MCs through onClipEvent can be spared from being reinitialized. The dynamically established MCs perform the above "initialization" because we configure the event code for them during operation.
How do we avoid this problem? In fact, there are too many methods, and many forums have also discussed it in extremely detailed terms, so I won’t go into details.
You may still remember what I just introduced, "Reading out-of-town data to participate in Flash application deployment is a very important and common task, especially when we often need to detect the progress of these data loading."
We have introduced several callback functions of MCL, so we won't go into details here. We are now creating such an effect: a thumbnail-like image browsing system. We are going to read some JPG images from outside and put them into our dynamically deployed MC. And we want these dynamically established MCs to have their own onPress events. We assign events to MC after it has loaded external resources.
Before we start, I would like to remind everyone to pay attention to some frequent omissions: be sure to set it to Flash7+AS2 or above when publishing; secondly, use the browser to test your effect, not the IDE; otherwise you will get strange results.
Now that we start coding, you will find it much simpler than you think.
1. Create a new Flash document.
2. Find four thumbnail pictures with 100*100 pixels.
3. Create a dynamic text box, about 300*300 pixels, use a font No. 12, and make it realistic borders, so that we can monitor it better. Don't forget to set it to multiple lines.
4. Create a 100X100 pixel rectangle, convert it to MC, and then move it out of the scene. At this time, he had already appeared in the library. In the library, set his link name "img" and make it "export in the first frame". In fact, this rectangle will be replaced when external resources are loaded, and now it is just for the convenience of debugging.
5. Create a new layer on the layer where the textBox text box was just placed. This layer is used to place our code. Write it first.
stop();
6. Now we define an instance of MCL, and in addition to define a basic object as our listener:
myMCL = new MovieClipLoader(); //define MovieClipLoader
myListener = new Object(); //define listener
7. Next, we use a listener to listen for the onLoadComplete event. The function of this event has been mentioned above. We now hand it over to the listener object, not the MCL instance. Of course, when you finally return the listener object to the MCL (to listen to its callback function), the effect you get is the effect we need.
Remember, only when the reading is completed, the deployment event tasks for MC are safe and reliable! Therefore, when onLoadComplete is triggered, the onPress event is deployed to the MC:
 = function(targetMC){
 += "LOADING OF " + targetMC
+ " COMPLETE" + newline;
 = function() {
 += newline
+ "targetMC = " + targetMC._name;
}
}
Note: Several lines in the above code have been artificially interrupted, but this does not affect the effect.
You may have noticed that the instance name of the MC is passed to onLoadComplete as an identity as a parameter when onLoadComplete is triggered, so it is very convenient for us to control the MC. For example, here you can use click MC to detect whether the event has been successfully deployed to the MC.
8. Now we build a function that contains a simple loop to deploy the MC on the scene. And timely allocate tasks (loadClip method) to read foreign resources for each deployed MC, the code is as follows:
function initClips(){
for (i=1; i<=4; i++){
("img", "img" + i, i);
this["img"+i]._x = i*110;
("0" + i + ".jpg" ,
this["img"+i]); //code wrapped
}
}
9. It’s basically done here. Now our remaining job is to register the listener and call the relevant functions and methods according to the requirements. The following two lines are reflected in the code:
(myListener);
initClips();
Note the order here, our listener object is used on the MCL instance before calling the initClip() function. Now our MC's onPress event can work smoothly, because the event is assigned to it only after the image is fully read. Our code is also very concise. We no longer have to make troubled loops for loading, MovieClipLoader helps us do all the work!
Attachment: The complete code is as follows:
stop();
myMCL = new MovieClipLoader();
myListener = new Object();
 = function(targetMC)
{
 = function ()
{
trace("pressed");
}
}
function initClips()
{
for (i=1;i<=4;i++)
{
("img","img"+i,i);
this["img"+i]._x = i*110;
(url,this["img"+i]);
}
}
(myListener);
initClips();
So far, you should believe that MCL is indeed a rare good thing, right? :)