Perfect loading-Perfect to the end

Source: Internet
Author: User
Tags contains resource setinterval what callback mymc3
Loading

First of all, I'd like to explain my motives for writing this article. I remember a long time ago I said "no loading flash, not full flash". I think that remark may have been extreme. Because sometimes some less than 10k of flash, do not need to do anything loading. But I always think that doing an excellent loading is a measure of a flasher level, even an attitude. You ask me why, I can tell you, because loading is the only one you will not see more and all users, customers will see things, so you pay attention to loading, you can even contrast this flasher professional ethics!

Some do design-oriented friends, I know a lot of them are loading attitude, do a loading, more is to find a ready-made, and then each to apply, I personally think it is very bad habits. Not that I do not advocate code, component reuse degree, but I think for loading this kind of thing, set many, is to have a problem. I strongly recommend that those who have reached the level of loading can be modified flasher look at my things, of course, if you do not even flash the as to write where you do not know, the proposal to start.

OK, here's how to make loading:

The first thing to be thankful for is the great wisdom of Macromedia, which provides a good two functions so that we can make the perfect loading, that is getbytesloaded and getbytestotal. Please do not use you change to change for two or three years of that what getframeloaded what, I can not remember how to spell. I just want to say that the idea of frame will fade in real interactive-design. Let alone what scene, that is Flash's failure!

So how does loading work? How do we use these two functions? There is an important concept to be mentioned here. is the interval call. Interval calls are in many ways, listed below, and enumerate their status and usage in loading production, welcome to add:

SetInterval Way

Writing:

function Loadcheck ()
{
var p = getbytesloaded ()/getbytestotal ();
if (p==1)
{
Clearinterval (Intervalid); Free interval Call
gotoAndPlay (Someframe); Start playing
}
}
var interval = 30; This number is the refresh rate.
var intervalid = setinterval (loadcheck,interval);

I personally do not recommend this for beginners. Because many people easily ignore clearinterval, and this thing is neglected, it is very scary! If your setinterval is not removed in time, that means you will add an unnecessary burden to the entire SWF playback process!
And this method is not suitable to control the situation of moiveclip (because beginners will find that the MC path is a big problem, and Loadcheck itself is a function, or is called by the setinterval, to the middle finger in loadcheck a path out, very troublesome, you do not expect _root, that will make your program not standard, and do not expect this, because it seems not ideal to use this in the function, it is best not to write, but often you dare not write, and then make better results.

Onenterframe Way

That's the way I like it best. More convenient and intuitive. Because often we are to use an MC to embody a loading progress, for example, a progress bar, or more creative things, only you can not think of, there is no you can not do.

So how to use it. First, set your ideas right. Then give your MC an instance name, like called LOADER_MC. This is the time to write code on the timeline, remember, is timeline rather than MC. Because it is easy to unify the code, convenient path unification, easy to manage and find. Don't move the code all the way to BUTTON,MC to save a few letters, and then one on (press). Unless you are working on your work, or you are trying to hand in your homework.

Loader_mc.onenterframe = function ()
{
var gettar:movieclip = this._parent;
var p = gettar.getbytesloaded ()/gettar.getbytestotal ();
Trace (P);
if (p==1)
{
This.onenterframe = null;
gotoAndPlay (Someframe); Start playing
}

}

It's so simple to remember that it's always a quick thing to refer to MC inside the MC's event function body. Because this can point to the MC itself, through methods such as this._parent, you can find all your mc!

• Directly dependent on the timeline cycle mode

Very very, very old way out, not introduced. But you can ask those who do not like to do their own loading flasher, they may be in a certain version of the change is this, hehe.

The above is relatively simple. It's easy to go wrong, there are two more.
First, Moviecliploader
Second, the loader containing a variety of V2 components

It is very important and common for us to read data from other cities to participate in Flash application deployment, especially when we need to detect the progress of these data loading. The Moviecliploader (hereinafter referred to as MCL) has helped us greatly simplify this troublesome task. In addition, it allows us to get more needs and reduce the amount of code. We can use a separate MovieClip class to load one or more out of the resources to a specified MC or hierarchy, or we can make a different MCL instance for each load job.

I decided to complete the tutorial in two parts. First, we will introduce the basic usage of MCL, and then we will explain how to use a separate MCL instance to read the different kinds of the MC, and we will join the listener object to participate in the work. Of course, the task can be accomplished without the listener, and we don't introduce the listener for the time being, because it makes it easier for you to understand MCL.

So, let's start with a general look at what callback functions MCL have, and there will be a detailed description (AW: The callback function I personally understand is that a certain class group, parameters in advance, with the specified effect of the method) here you can find out what is called a callback function:

callback function for Moviecliploader object:

Event callback functions (when strict data types are required, they are not methods, post-Xiang):
* Moviecliploader.onloadstart ()-Triggers when loading starts
* Moviecliploader.onloadprogress ()-Trigger in read
* MOVIECLIPLOADER.ONLOADINIT ()-triggers after the first frame execution completes after the resource load is read
* Moviecliploader.onloadcomplete ()-triggers when the read out of the local resource has been completely downloaded to the native.
* MOVIECLIPLOADER.ONLOADERROR ()-triggered when there is an error loading an out-of-town resource.
* Moviecliploader.unloadclip ()-removes or terminates a loading operation on the loaded out-of-town resources.

Method callback function:

* Moviecliploader.getprogress (Target:object): Object-Read the progress of the resources in the other cities, the parameters are MC objects (AW attached: In fact, MC This type of data is also an object). Returns an object that contains two predefined attributes (after-xiang)

To get a good understanding of these callback functions, it's best to experiment. Of course MCL is Flash7, so don't forget to release it as 7+ version number. If the direct use of Flashplayer to debug may encounter some problems, we recommend debugging in the browser (personal opinion: for the resources of other cities are difficult to obtain, such as education network access to public resources, preferably not in the IDE debugging)

In our example, we will use a MCL object to read different pictures and place them in different empty MC. The SWF file and image source file to be used in this example will be found in actionscript.org (personal suggestion: actually read this article do not need source file)

1. Create a new Flash document and enter the following script in frame 1th:

_root.tracebox.vscrollpolicy = "on";
function Mytrace (msg)
{
_root.tracebox.text + + msg + newline;
_root.tracebox.vposition = _root.tracebox.maxvposition;
}

We are here to establish a tracking debugging mechanism, the debugging (variable) will be output to the text box component. The method "Mytrace" Here is a predefined function that helps us to successfully monitor certain information; the second sentence is to make the text box output the latest monitoring value at any time.

2, now from the build library to drag a textarea component into the scene, and give the appropriate size, and an instance name Tracebox (corresponding to the above script)

3. Next, we will build a new MC component. and deploy 3 instances on the scene, named Mymc1,mymc2,mymc3 for them respectively. We will load the pictures or SWF movies into them and, when they are downloaded locally, resize them as needed. In fact, to change the size of the image artificially will cause many bad consequences, such as the emergence of sawtooth, but in order to let everyone understand the use of Onloadinit events, we will do so.

4, then, we create a MCL object, enter the following script in the first frame:

var mymcl = new Moviecliploader ();//create an instance of Moviecliploader

AW attachment: Here I would like to Russell below, about the translation of object. Because the above code annotation, the foreigner uses the Word instance, literal translation words, object is "Object"; instance represents "instance". The former pays more attention to its data type, while the latter pays more attention to its objective existence.

5. Now we can deploy the script in the first frame:

Mymcl.onloadstart = function (TARGETMC)
{
var loadprogress = mymcl.getprogress (TARGETMC);
Mytrace ("The MovieClip" + TARGETMC + "has started loading");
Mytrace ("Bytes loaded at start=" + loadprogress.bytesloaded);
Mytrace ("Total bytes loaded at start=" + loadprogress.bytestotal);
}

The first line of the function declares a variable (object type), and obviously the value of the variable is obtained by the Getprogress method of the Mymcl object. Just now we've introduced the Getprogress method, and here's what you can see, The loadprogress.bytesloaded returned is the Bytesloaded property of the Loadprogress object.
Here's another word: Why return an object without returning a specific value. There is a reason for that. function return value makes programming more perfect, but 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, it is returned only through the form of an object. This is the simplest and most efficient way to solve a problem. The following three lines of Mytrace echo the previously defined monitoring function, so that we can see the variables we are focusing on.

6. We have deployed the appropriate work for the Onloadstart event, and then we will deploy for the other events mentioned above. followed by the Onloadprogress, which received three parameters: TARGETMC, Loadedbytes, TotalBytes. Represents the target Container MC instance, the volume and total volume that has been read.

mymcl.onloadprogress = 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 accepts only one parameter, it is the container MC instance. Like Onloadstart, we use the Getprogress method to return the read.

Mymcl.onloadcomplete = function (TARGETMC)
{
var loadprogress = mymcl.getprogress (TARGETMC);
Mytrace (TARGETMC + "has finished loading.");
Mytrace ("Bytes loaded at end=" + loadprogress.bytesloaded);
Mytrace ("Bytes total at end=" + loadprogress.bytestotal);
}

8. The Onloadinit method will not begin executing until all loaded content is downloaded to the local container MC. This will allow you to better control the properties of the content that is loaded in. The picture I chose was very large so that we could see the reading process more clearly, and I had to trim the size of the picture that was already loaded so that it could be displayed.

Mymcl.onloadinit = 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 a good programmer, when deploying a perfect application, it is essential to avoid the mistakes that occur!

Mymcl.onloaderror = function (TARGETMC, errorcode)
{
Mytrace ("errorcode:" + errorcode);
Mytrace (TARGETMC + "Failed to load its content");
}

The hard work out of the way. Now we just have to load the files of their respective targets, using Loadclip, and passing it two arguments:the Ion of your file, and the destination movieclip for the "file to load in".
10, we finally put the most complex work deployed. Next we'll just read what we need using the Loadclip method. The two parameters of Loadclip method are the address of the resources in the cities and the example of container MC respectively.

Mymcl.loadclip ("http://www.yourdomain.com/test1.swf", "_ROOT.MYMC1");
Mymcl.loadclip ("http://www.yourdomain.com/test2.swf", "_ROOT.MYMC2");
Mymcl.loadclip ("Http://www.yourdomain.com/pic.jpg", "_LEVEL0.MYMC3");

The path can select a relative path. Note that the relativity of the path is also a big problem, when the SWF is referenced in HTML that is not in this path, follow the path of the HTML! This is a point that many flash tutorials have overlooked. Therefore, sometimes absolute paths also have the advantage of absolute paths. [path problem source file download, download a glance at the

All debugging work is best done in the browser, not the IDE. And the script output must be AS2.
Remember, for everything to work properly your need to is testing throuhg a browser (and preferably on line so you can The files loading in real time). You are also need to be exporting your code as ActionScript 2.

In the "second part of" This tutorial I ' m going to show you with the Moviecliploader class in a real-world situation, In the order to solve a common problem when assigning event handlers to movieclips dynamically.
Next, I'll describe the situation where you call MCL in real time. In order to adapt to more applications, we often work on a dynamic basis for MCL.

AW narrating: Sometimes, we write this:

1, var mcl:moviecliploader = new Moviecliploader ();
2, var mcl = new Moviecliploader ();

found that the first method can not be used for MCL to develop Onloadstart and other event methods. This is the problem that the compiler generates based on the data type of the specified variable. Osflash some friends gave some useful ideas, I also found that this problem is related to flash internal incident response mechanism, may wish to introduce:
Three kinds of event response mechanism in Flash

1, the simple callback function, the oldest;
2, listener, ASBROADCASTER,FLASHMX times;
3, event listeners, eventdispather,flashmx2004 times

Here, MCL uses the second mechanism, while the entire V2 component uses the last set of mechanisms.
attached: MCL Official statement, note: The above method, only contains 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 added that : 1, 2 when not strict requirements of data types can be universal.

The following is an introduction to the method of detecting MCL events with listeners. Before we solve one of the most common problems, we often see someone ask this question in a forum:

Reference:

Hello everyone, I have dynamically built some MC and assigned each of them an event handle (flag). Then I read the resources out of the cities. But these allocated event handles are not working!
Then, the questioner usually pastes a pair of messy code and cries for help.

So, let's first analyze the reason for this error: The MC will be reinitialized when the resource is loaded into an MC. This means that any code that has been prepared in advance will be in vain. There is no trouble with the MC that developers have manually arranged on the stage, because any code that passes directly through the onclipevent to the MC is immune to reinitialization. The dynamically established MC carries out the above "initialization" because we are configuring the event code for them in the run.

How can we avoid this problem? In fact, the method is too much, many forums have also been very detailed discussion, I do not have to repeat.

Now, you may remember the "read out of the data to participate in the Flash application deployment is a very important and common work, especially we often need to detect the progress of these data loading "

We've introduced several callback functions for MCL, so we're not going to repeat them here. We are now making an effect: the thumbnail icon-style image browsing system. We're going to read some JPG images from the outside and put them in our dynamically deployed MC. And we want these dynamically established MC to have their own onpress events. We assign events to the MC by loading the external resources.

Before we begin, I would also like to remind you of some of the frequent omissions: Be sure to set the FLASH7+AS2 version at the time of release; second, use your browser to test your effects, not the IDE; otherwise you will get strange results.

Now that we start coding, you'll find it much simpler than you think.

1, create a new flash document.

2, find four pieces of 100*100 pixel thumbnail image.

3, create a dynamic text box, probably in the 300*300 pixel around, use font 12th, and make the reality of the border, so we better monitor. Don't forget to set it as multiple lines.

4, create a 100x100 pixel rectangle, convert to MC, and then move it out of the scene. By 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 the external resource is loaded, and now it is just for debugging convenience.

5. Create a new layer on top of the layer where you just placed the TextBox text box, which is used to place our code, first write:

Stop ();

6. Now we define a MCL instance, and define a basic object as our listener:

MYMCL = new Moviecliploader (); Define Moviecliploader
MyListener = new Object (); Define Listener

7. Next we use listeners to listen for onloadcomplete events, which are mentioned above. We now give it to the listener object, not the MCL instance. Of course, when the listener object is eventually returned to the MCL (to listen for its callback function), the result is the effect we need.

Remember, only when the completion of the reading, the MC deployment event task is safe and reliable! Therefore, the Onpress event is deployed to the MC when the Onloadcomplete is triggered:

Mylistener.onloadcomplete = function (TARGETMC) {
Debug.text + = "LOADING of" + TARGETMC
+ "COMPLETE" + newline;
targetmc.onpress = function () {
Debug.text + + newline
+ "TARGETMC =" + targetmc._name;
}
}

Note: several lines in the above code are interrupted artificially, but this does not affect the effect.

You may have noticed that the instance name of the MC is passed to the Onloadcomplete as a parameter when the onloadcomplete is triggered, so it is very convenient for us to control the MC. For example, here you can use the MC to detect whether the event was successfully deployed to the MC.

8. Now we build a function that contains a simple loop to deploy the MC on the scene. And in a timely manner for each of the deployment of a good MC assigned to read the task of the other resources (Loadclip method), the code is as follows:

function Initclips () {
For (I=1 i<=4; i++) {
This.attachmovie ("img", "img" + i, I);
This["img" +i]._x = i*110;
Mymcl.loadclip ("0" + i + ". jpg"),
This["img" +i]); Code wrapped
}
}

9, here is basically done. Now the rest of our job is to register the listener and call the relevant functions and methods on demand, reflecting the following two lines of code:

Mymcl.addlistener (MyListener);
Initclips ();

Notice the order here, our listener object is acting on the MCL instance before invoking the Initclip () function. Now our MC's Onpress event can work smoothly, because when the picture is fully read, the event is assigned to the past. Our code is also very concise. We no longer need to loading to make trouble cycle, Moviecliploader help us to complete all the work!

attached: complete code as follows:

Stop ();
MYMCL = new Moviecliploader ();
MyListener = new Object ();
Mylistener.onloadcomplete = function (TARGETMC)
{
targetmc.onpress = function ()
{
Trace ("pressed");
}
}

function Initclips ()
{
for (i=1;i<=4;i++)
{
This.attachmovie ("img", "img" +i,i);
This["img" +i]._x = i*110;
Mymcl.loadclip (url,this["img" +i]);
}
}
Mymcl.addlistener (MyListener);
Initclips ();

So far, you should believe that MCL is really a rare good thing, right?

V2, also love, also hate! Here is a description of the loading problem with the V2 component project

The V2 component has been controversial since its inception and is broadly summarized as follows:

Advantages:

1, interface than V1 components more beautiful, unified, more perfect human-machine interaction mode
2, all adopt object-oriented script deployment

Disadvantages:

Bulky, it is awkward to develop small applications that use only one or two components.

The message mechanism uses Eventdispather message broadcast mechanism to replace the original asbroadcast mechanism. So many people just don't use it when they come out.

There is no more discussion here, let's say loading. Products containing a large number of V2 components to see people must be loading, such as AW ' s blog on the left of the blog tips. However, every time in the loading seems to have trouble. That is, the bulky volume is all put into the first frame of the export, resulting in some 300k, containing V2 components of the SWF file for remote loading loading effect becomes stretched.

The solution is not no, simply summed up as three steps:

One, remove "Export in the first frame"

Second, in the release of the time set "Export Frame for classes", this is very important!

Third, for the reading of the SWF file containing V2, the container MC for the following settings:

Loader_mc._lockroot = true;

OK, now enjoy the wonderful and bulky V2 components ~!



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.