In all of the previous sections at this site (except site structure 2), we've looked at building Flash movies by drawing or importing content into the movie (via the Flash IDE) and putting it on stage and/or in the library. But content can also be added to Flash at runtime. You can use the createEmptyMovieClip method to create movieclips dynamically that can serve as holders for externally loaded content or use the drawing API to draw vector content in the created movieclips. You can create textfields dynamically by using the createTextField method. All of these commands (createTextField, createEmptyMovieClip, and the drawing API commands) are executed as soon as they are encountered by the Flash interpreter and finish executing before the next statement in the movie is encountered. So you can say, for example,
createTextField("dynamic_txt", 1, 10, 10, 150, 30); dynamic_txt.text = "Here's some text"; x = 5;
and know that a textfield named dynamic_txt will be created on stage and the text "Here's some text" appear in it before variable x is set to 5.
You can also add instances of movieclip symbols in the library to the stage dynamically using the attachMovie method, another example of a command which is executed immediately.
Other commands allow you to load external swfs or jpgs from the web server into a Flash movie dynamically, and to read XML files or request data from a web server. These commands are carried out asynchronously -- that is, the command is executed as soon as the interpreter encounters it, but it may not (and probably won't) be complete before the next statement in the program is read and interpreted if the Flash movie is running online. Thus you cannot put statements which depend on those operations being complete in lines that immediately follow the command to load the jpg or read the XML file. Instead, such situations are dealt with in Flash MX 2004 by using classes that were specifically designed for each of these situations, which allow a function to be executed only when the operation has been completed (either successfully, or some error condition is encountered).
This adds an extra layer of complexity to your program flow --when loading external content, you cannot simply put statements into the Flash movie and expect that they will all happen one after the other--, and requires that you pay particular attention to the issues of scope and correct addressing of instances that we discussed on previous pages. In the following pages, we'll look at the MovieClipLoader class, which handles asynchronous loading of swfs and jpgs, and the XML class, whose onLoad method is used to define what will happen when the XML file has been read.
Discussed on this page:
including dynamic content, asynchronous events