View comments | RSS feed

Loading an external SWF file

In ActionScript 3.0, SWF files are loaded using the Loader class. To load an external SWF file, your ActionScript needs to do four things:

  1. Create a new URLRequest object with the url of the file.
  2. Create a new Loader object.
  3. Call the Loader object's load() method, passing the URLRequest instance as a parameter.
  4. Call the addChild() method on a display object container (such as the main timeline of a Flash document) to add the Loader instance to the display list.

Ultimately, the code looks like this:

var request:URLRequest = new URLRequest("http://www.[yourdomain].com/externalSwf.swf");
var loader:Loader = new Loader()
loader.load(request);
addChild(loader);

This same code can be used to load an external image file such as a JPEG, GIF, or PNG image, by specifying the image file's url rather than a SWF file's url. A SWF file, unlike an image file, may contain ActionScript. Thus, although the process of loading a SWF file may be identical to loading an image, when loading an external SWF file both the SWF file doing the loading and the SWF file being loaded must reside in the same security sandbox if you plan to use ActionScript to communicate in any way to the external SWF file. Additionally, if the external SWF file contains classes that share the same namespace as classes in the loading SWF file, you may need to create a new application domain for the loaded SWF file in order to avoid namespace conflicts. For more information on security and application domain considerations, see Using the ApplicationDomain class and Loading SWF files and images.

When the external SWF file is successfully loaded, it can be accessed through the Loader.content property. If the external SWF file is published for ActionScript 3.0, this will be either a movie clip or a sprite, depending on which class it extends.

Considerations for loading an older SWF file

If the external SWF file has been published with an older version of ActionScript, there are important limitations to consider. Unlike an ActionScript 3.0 SWF file that runs in AVM2 (ActionScript Virtual Machine 2), a SWF file published for ActionScript 1.0 or 2.0 runs in AVM1 (ActionScript Virtual Machine 1).

When an AVM1 SWF file is successfully loaded, the loaded object (the Loader.content property) will be an AVM1Movie object. An AVM1Movie instance is not the same as a MovieClip instance. It is a display object, but unlike a movie clip, it does not include timeline-related methods or properties. The parent AVM2 SWF file will not have access to the properties, methods, or objects of the loaded AVM1Movie object.

There are additional restrictions on an AVM1 SWF file loaded by an AVM2 SWF file. For details, see the AVM1Movie class listing in the ActionScript 3.0 Language and Components Reference.


Flash CS3


Comments


No screen name said on Jun 8, 2007 at 7:16 AM :
To use timeline-related methods or properties, cast the loader.content to MovieClip.

Example:

// Make request and loader
var request:URLRequest = new URLRequest("http://www.[yourdomain].com/externalSwf.swf");
var loader:Loader = new Loader();

// This is done after the swf is loaded.
function finished_loading (e:Event) {
var externalMovie = MovieClip(loader.content); // cast 'DisplayObject' to 'MovieClip'
stage.addChild(externalMovie); // add your swf directly to the stage
externalMovie.gotoAndPlay("start"); // Now you can use all MovieClip methods!
}

// Tell the loader to call 'finished_loading' after the swf is loaded.
import flash.events.Event;
loader.contentLoaderInfo.addEventListener(flash.events.Event.COMPLETE, finished_loading);

// Start loading.
loader.load(request);
malachite00 said on Jul 10, 2007 at 11:14 AM :
Thank you for the above comment. I've looked everywhere trying to find how to control the loaded swf.
No screen name said on Jul 18, 2007 at 9:40 PM :
thanks so much for the comment above - it was extremely helpful
bcorn77 said on Aug 4, 2007 at 3:40 PM :
Although the documentation doesn't mention it, other elements in a loaded swf file that are created by the designer can also be manipulated. Say for example that you wanted to load a menu swf file into a main swf file, and have a callback function called in the main swf whenever a button in the menu swf is clicked so you can replace the menu with another section (thus allowing you to create websites where each section is loaded on demand so download times are minimized, and you can create entire websites using flash). Check out the following code which is defined on a single frame in the main swf's timeline:

/* GLOBAL VARIABLES */
/* -------------------------------- */
var ldr:Loader = new Loader();

/* FRAME SPECIFIC CODE */
/* -------------------------------- */
loadMenu();
stop();

/* FUNCTION DEFINITIONS */
/* -------------------------------- */

// Function that loads the main menu:
function loadMenu():void {
var url:String = "/home/menu.swf";
var urlReq:URLRequest = new URLRequest(url);
movPreloader.visible = false;
ldr.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress_Loader);
ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete_Loader_Menu);
ldr.load(urlReq);
addChild(ldr);
}

// Function that loads the different sections (other than the main menu):
function loadSection(strURL:String):void {
ldr.unload(); // unload the previously loaded section.
var urlReq:URLRequest = new URLRequest(strURL);
movPreloader.visible = false;
ldr.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress_Loader);
ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete_Loader_Section);
ldr.load(urlReq);
addChild(ldr);
}

/* CALLBACK FUNCTION DEFINITIONS */
/* -------------------------------- */

// Callback function which displays and updates the preloader while the loader
// object is loading and hides the preloader upon completion:
function onProgress_Loader(event:ProgressEvent):void {
movPreloader.visible = true;
var nStatus:int = Math.round(((event.bytesLoaded / event.bytesTotal) * 100));
movPreloader.movGolfAnimation.movGolfBall.x = 0.8 + (nStatus * 2.85);
var strStatus = nStatus.toString() + "%";
movPreloader.movGolfAnimation.movGolfBall.strBallProgress.text = strStatus;

if (nStatus == 100) {
movPreloader.visible = false;
ldr.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, onProgress_Loader);
}
}

// Callback function which is called after the menu has completed loading:
function onComplete_Loader_Menu(event:Event):void {
var extmov = MovieClip(ldr.content); // cast 'DisplayObject' to 'MovieClip'

// Add event listeners for all of the buttons in the menu:
extmov.btnContact.addEventListener(MouseEvent.CLICK, onClick_btnContact);
extmov.btnShop.addEventListener(MouseEvent.CLICK, onClick_btnShop);
extmov.btnLessons.addEventListener(MouseEvent.CLICK, onClick_btnLessons);
extmov.btnPractice.addEventListener(MouseEvent.CLICK, onClick_btnPractice);
extmov.btnSpecialty.addEventListener(MouseEvent.CLICK, onClick_btnSpecialty);

// Remove this event listener now that we're finished with it:
ldr.contentLoaderInfo.removeEventListener(Event.COMPLETE, onComplete_Loader_Menu);
}

// Callback function which is called after a section other than the main menu
// has finished loading:
function onComplete_Loader_Section(event:Event):void {
var extmov = MovieClip(ldr.content); // cast 'DisplayObject' to 'MovieClip'

// Add an event listener for the button in each section that returns
// the user to the main menu:
extmov.btnMenu.addEventListener(MouseEvent.CLICK, onClick_btnMenu);

// Remove this event listener now that we're finished with it:
ldr.contentLoaderInfo.removeEventListener(Event.COMPLETE, onComplete_Loader_Section);
}

// Callback functions for the menu:
function onClick_btnContact(event:MouseEvent):void {
loadSection("/home/contact.swf");
}

function onClick_btnShop(event:MouseEvent):void {
loadSection("/home/shop.swf");
}

function onClick_btnLessons(event:MouseEvent):void {
loadSection("/home/lessons.swf");
}

function onClick_btnPractice(event:MouseEvent):void {
loadSection("/home/practice.swf");
}

function onClick_btnSpecialty(event:MouseEvent):void {
loadSection("/home/specialty.swf");
}

// Callback function for the button in each section that
// takes the user back to the menu:
function onClick_btnMenu(event:MouseEvent):void {
ldr.unload();
loadMenu();
}
No screen name said on Aug 20, 2007 at 12:41 AM :
TypeError: Error #1034: Type Coercion failed: cannot convert
flash.display::AVM1Movie@4543ca51 to flash.display.MovieClip.
at myflashmoviename_fla::MainTimeline/finished_loading()

This is what I got when I tried to load an external menu .swf using the
code in the first post.

Can anybody help?
bdz said on Sep 28, 2007 at 4:28 AM :
you're probably loading a non-flash 9 version swf
b_oliver said on Oct 3, 2007 at 12:05 AM :
I have a similar error using a flash 9 swf

TypeError: Error #1034: Type Coercion failed: cannot convert flash.display::Loader@12dff9d1 to mx.core.IUIComponent.
adbe_paul said on Oct 3, 2007 at 2:35 PM :
@b_oliver:
Since the error message mentions mx.core.IUIComponent, I assume you're trying to load a SWF and then add it to a Flex application. In Flex, you'll want to use the Image control (mx.controls.Image) or the SWFLoader control (mx.controls.SWFLoader) to load a SWF, even if you created it in Flash.

The following page gives more information about using the SWFLoader control, and links to info about the Image control also:
http://livedocs.adobe.com/flex/201/html/controls_059_17.html
No screen name said on Dec 27, 2007 at 8:59 AM :
I am getting a type coercion error # 1034 when trying to set a property on a loaded swf that has a custom document class. I'm using the Loader class to load the swf, attaching an event handler to the Event.INIT event, and that event handler attempts to set a property on the custom document class that is backing the loaded swf. More background ... in the event handler, if I perform an "is" check of the event.target.content as MovieClip it's true, but if I perform an "is" check of the .content against my custom class, it's false. What gives?
oliverbob said on Jan 2, 2008 at 12:12 AM :
This file will work if you import this from your calling flash file.
the calling as file should have a code like this:
step1(true);
package {
import flash.display.MovieClip;
import com.FlexApp.as3App.PhotoViewer.ui.LoadMovie;


public class CallMovie extends MovieClip {

private var _loadMv:LoadMovie;

public function CallMovie() {
_loadMv = new LoadMovie();
addChild(_loadMv);
_loadMv.preload = "../Recording/test.swf";
//trace(_loadMv);
}
}
}


step2(true);

If you are not using flex, then you must create a .fla file and publish it with a black or dark background with. Make sure that under the properties menu you key in this value: "CallMovie" without qoutes. The .swf file that you will publish must reside where your "com" dircetory is relatively located. If step2(false) for you, go to step3(true, FLEX);


step3(true, FLEX);

Be sure that the next file is located in the directory: com/FlexApp/as3App/PhotoViewer/ui
Here is the file which you have to call:

package com.FlexApp.as3App.PhotoViewer.ui{
import flash.display.MovieClip;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.events.ProgressEvent;
import flash.display.LoaderInfo;
import flash.filters.DropShadowFilter;
import flash.filters.BevelFilter;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.display.Shape;

public class LoadMovie extends MovieClip {

public var _preloader:Loader;
private var _swfFile:String;
private var url:String;
private var _loaderText:TextField;
private var _shapeProgress:Shape;
private var _n:Number;
public var _loadedFile:Loader;

public function get preload():String {
return _swfFile;
}
public function set preload(value:String):void {
if (value != "Images/Vacation1.jpg") {
//value = "preloader_mc.swf"; //"C:/Documents and Settings/Upgrade Needed/Desktop/
}
_swfFile = value;
preloader(value);// String
//dispatchEvent(new Event("change"));
_shapeProgress = new Shape();
_shapeProgress.graphics.lineStyle(5, 0xFFFFFF, 1);
_shapeProgress.graphics.beginFill(0xFFFFFF, 1);
_shapeProgress.graphics.endFill();
_n = new Number;
_n = 1;

addChild(_shapeProgress);
_shapeProgress.x = 170;
_shapeProgress.y = 20;
}
public function LoadMovie() {
url = _swfFile;
_loaderText = new TextField();
_loaderText.autoSize = TextFieldAutoSize.CENTER;
_loaderText.background = false;
_loaderText.border = false;
_loaderText.x = 200;
_loaderText.y = 30;

var format:TextFormat = new TextFormat();
format.font = "Verdana";
format.color = 0xcccccc;
format.size = 10;
format.underline = false;

_loaderText.defaultTextFormat = format;
addChild(_loaderText);
}

public function preloader(url:String):void {
_loadedFile = new Loader();
addChild(_loadedFile);
var request:URLRequest = new URLRequest(url);// String
_loadedFile.load(request);
_loadedFile.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoad);
_loadedFile.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
_preloader = _loadedFile;
}
private function onCountFinish(event:TimerEvent):void {
}
public function onTimerEvent(event:TimerEvent):void {
//dispatchEvent(new Event(Event.CHANGE));
}
private function onLoad(event:Event):void {
_preloader.width = 550;
_preloader.height = 400;
addChild(_loadedFile);
/*_preloader.x = 450;
_preloader.y = 65;*/
var dropShadow:DropShadowFilter = new DropShadowFilter();
dropShadow.angle = 40;
var bevel:BevelFilter = new BevelFilter();
_preloader.filters = [dropShadow];
_preloader.filters = [bevel];
addChild(_loaderText);
addChild(_shapeProgress);
removeChild(_loaderText);
removeChild(_shapeProgress);
dispatchEvent(new Event("change"));
}
public function onProgress(event:ProgressEvent):void {
addChild(_loaderText);
addChild(_shapeProgress);

var timer:Timer = new Timer(1000, 10);
timer.addEventListener(TimerEvent.TIMER, onTimerEvent);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, onCountFinish);
//timer.start();

var loaderInfo:LoaderInfo = LoaderInfo(event.target);
var percent:String = new String;
percent = " % loaded";
_loaderText.text = "" + ((loaderInfo.bytesLoaded) / (loaderInfo.bytesTotal) * 100);
_loaderText.text = (uint(_loaderText.text)+percent/* + " % loaded of " + loaderInfo.bytesTotal + " bytes Bob."*/);
dispatchEvent(new Event(Event.CHANGE));
var st:String = new String;
st = "" + ((loaderInfo.bytesLoaded) / (loaderInfo.bytesTotal) * 100);
var lodBal:uint;
lodBal = ((loaderInfo.bytesLoaded) / (loaderInfo.bytesTotal) * 100);
st = uint(st)+" s";
_loaderText.text == st+percent;
_shapeProgress.graphics.lineTo(lodBal, 0);
}
}
}

step(4);
Makesure that your ../Recording/test.swf exist withing whatever directory you will specify.

finally("edit the x and y property or distribute your application Give thanks to God since it is free ok?");

If you have questions, please feel free to email me at oliverbobonline@gmail.com
sabird said on Jan 17, 2008 at 12:48 PM :
I am having the exact same problem, verbatim, as described in the post
above:

==========
I am getting a type coercion error # 1034 when trying to set a property on a
loaded swf that has a custom document class. I'm using the Loader class to
load the swf, attaching an event handler to the Event.INIT event, and that
event handler attempts to set a property on the custom document class that
is backing the loaded swf. More background ... in the event handler, if I
perform an "is" check of the event.target.content as MovieClip it's true, but if I
perform an "is" check of the .content against my custom class, it's false. What
gives?
==========

Has anyone found a solution to this problem? It would be a fantastic help to
me if you have. It seems like there should be a simple fix somehow. But I
guess appearances could be deceiving.

Thanks in advance.
No screen name said on Apr 23, 2008 at 7:46 PM :
Hi,

I am trying to link a button to a frame in my flash document. Here is my code
for the button.

stop();
import flash.events.MouseEvent;
BlueButton.addEventListener(MouseEvent.CLICK,doClick);
function doClick(e:MouseEvent):void
{
gotoAndStop(10);
}

When I test my movie, I get this error:


TypeError: Error #1034: Type Coercion failed: cannot convert
flash.display::SimpleButton@1c4ce7b1 to flash.display.MovieClip.

Please help: what am I doing wrong?

thanks

 

RSS feed | Send me an e-mail when comments are added to this page | Comment Report

Current page: http://livedocs.adobe.com/flash/9.0/main/00000216.html