Load an external text/html file using ActionScript 3, sample code.

[ Discuss this code in my forums ]

I have decided to start posting some of my code snippets that help me on a regular basis, and now that I have started using Code Collector Pro, I hope to finally keep them all in one place. So in the spirit of sharing the code here is some ActionScript 3 code that loads an external text file ready to be used in a TextField or anything else you need content for.

———– code sample

function textLoadComplete(event:Event):void
{
        // Some code to do something with the loaded text
        // For example you have a text field instance called
        // myTextField, so you could do
        // myTextField.text = textLoader.data;
        // or for HTML text
        // myTextField.htmlText = textLoader.data;

        trace(textLoader.data);
}

var textLoader:URLLoader = new URLLoader();
var textReq:URLRequest = new URLRequest(“path_to_file”);

textLoader.load(textReq);
textLoader.addEventListener(Event.COMPLETE, textLoadComplete);

———– end code sample

Basically you create an instance of the URLLoader and URLRequest classes and then tell them to load the file and have an EventListener call a method/function and do something with the loaded content. The event Event.COMPLETE only executes after successfully loading the complete file requested.

Published by Peter Witham

Web applications developer & designer. Certified Flash Designer.

44 thoughts on “Load an external text/html file using ActionScript 3, sample code.

  1. This was helpful. Thanks. I think you need to change the name of the function you call textLoadComplete to the function you made and capitalize the T in htmlText.

  2. Thanks champ I was looking around for something like this, very helpful. I’m going to implement this on a few of my sites
    -Thanks

  3. Hi
    Thanks for the tip, it’s very useful. However, I experienceof additionnal line breaks in my imported external HTML file. Do you know how to remove them?
    Thanks
    David

  4. David i would use the HTML Loader and not the text loader. This way you will get the exact display your looking for. However i do not have the code for AS3 “HTMLLoader”

  5. You can remove the additional line breaks with the “split” and “join” String functions.
    In the above example this will be
    myTextField.htmlText = textLoader.data.split(“\r\n”).join(“\n”);
    or use the data from the event via
    myTextField.htmlText = event.target.data.split(“\r\n”).join(“\n”);

    Regards,

    Kurt.

  6. Hello,

    I am an artist, brand new to AS3, been learning it only a couple of days.

    I’m wondering if you could help simplify this code from this post a bit for me, so I can more easily apply it to my website. I’m confused. 😦

    I have a dynamic text box with an instance name of homeText

    I have a file stored on my web server named homeText.txt

    What would I use for AS3, and where would I put it in my actionscript?

    the website I am testing is at http://www.adamkaz.com/jeff, and you can see the text box.

    This is what the “main” AS3 is for me:

    stop();

    bio_btn.addEventListener(MouseEvent.MOUSE_DOWN, gobio);
    function gobio(event:MouseEvent):void {
    gotoAndPlay(“bio”);
    }

    home_btn.addEventListener(MouseEvent.MOUSE_DOWN, gohome);
    function gohome(event:MouseEvent):void {
    gotoAndPlay(“home”);
    }

    listen_btn.addEventListener(MouseEvent.MOUSE_DOWN, golisten);
    function golisten(event:MouseEvent):void {
    gotoAndPlay(“listen”);
    }

    contact_btn.addEventListener(MouseEvent.MOUSE_DOWN, gocontact);
    function gocontact(event:MouseEvent):void {
    gotoAndPlay(“contact”);
    }

    links_btn.addEventListener(MouseEvent.MOUSE_DOWN, golinks);
    function golinks(event:MouseEvent):void {
    gotoAndPlay(“links”);
    }

  7. @Adam,

    You would want to put the code to load the text file content on the first frame of the timeline so the process of loading the data starts as soon as the swf file is loaded into the browser.

    And have the instance homeText.text set to the data loaded for example

    function textLoadComplete(event:Event):void
    {
    homeText.text = textLoader.data;
    }

    This would populate your text instance with the data after it has been loaded.

    hope this helps,
    Peter.

  8. Here ya go!
    stop();
    var cssUrl:URLRequest = new URLRequest(“default.css”);
    var cssLoader:URLLoader = new URLLoader();
    cssLoader.load(cssUrl);
    cssLoader.addEventListener(Event.COMPLETE,cssLoaded);

    function cssLoaded(event:Event):void {
    var css:StyleSheet = new StyleSheet();
    css.parseCSS(URLLoader(event.target).data);
    tField.styleSheet = css;
    }
    var textUrl:URLRequest = new URLRequest(“01.txt”);
    var textLoader:URLLoader = new URLLoader();
    textLoader.load(textUrl);
    textLoader.addEventListener(Event.COMPLETE,fileLoaded);

    function fileLoaded(event:Event):void {
    tField.htmlText= event.target.data;
    tField.background = false;
    tField.backgroundColor = 0x333333;
    tField.textLoader.removeEventListener(Event.COMPLETE, fileLoaded);
    }

    // create two files default.css and 01.txt.. i have actually organized them into their own folders.
    //Second place a dynamic text field on your stage where the code is located and give the instance name of tField

    Mahalo

  9. OOOPS FIX!!!! REMOVE tField from tField.textLoader.removeEvent ……
    I also added a word wrap.
    _____________________________________
    stop();
    var cssUrl:URLRequest = new URLRequest(“css/default.css”);
    var cssLoader:URLLoader = new URLLoader();
    cssLoader.load(cssUrl);
    cssLoader.addEventListener(Event.COMPLETE,cssLoaded);

    function cssLoaded(event:Event):void {
    var css:StyleSheet = new StyleSheet();
    css.parseCSS(URLLoader(event.target).data);
    tField.styleSheet = css;
    }
    var textUrl:URLRequest = new URLRequest(“home/home.txt”);
    var textLoader:URLLoader = new URLLoader();
    textLoader.load(textUrl);
    textLoader.addEventListener(Event.COMPLETE,fileLoaded);

    function fileLoaded(event:Event):void {
    tField.htmlText= event.target.data;
    tField.background = false;
    tField.backgroundColor = 0x333333;
    tField.wordWrap = true;
    textLoader.removeEventListener(Event.COMPLETE, fileLoaded);
    }

    // create two files default.css and 01.txt.. i have actually organized them into their own folders.
    //Second place a dynamic text field on your stage where the code is located and give the instance name of tField

    Mahalo

  10. hi,

    i have used the code but i am facing a problem that when i am using it in browser the scrollbar is deactivated i.e. not working

    var cssUrl:URLRequest = new URLRequest(“dk.css”);
    var cssLoader:URLLoader = new URLLoader();
    cssLoader.load(cssUrl);
    cssLoader.addEventListener(Event.COMPLETE,cssLoaded);

    function cssLoaded(event:Event):void {
    var css:StyleSheet = new StyleSheet();
    css.parseCSS(URLLoader(event.target).data);
    tField.styleSheet = css;
    }
    var textUrl:URLRequest = new URLRequest(“sample.htm”);
    var textLoader:URLLoader = new URLLoader();
    textLoader.load(textUrl);
    textLoader.addEventListener(Event.COMPLETE,fileLoaded);

    function fileLoaded(event:Event):void {
    tField.htmlText= event.target.data;
    tField.background = false;
    tField.wordWrap = true;
    textLoader.removeEventListener(Event.COMPLETE, fileLoaded);
    }

    kindly help me

  11. This script is not working for me. I must have something wrong:

    function textLoadComplete(event:Event):void
    {
    synopsisBox.text = textLoader.data;
    }

    var textLoader:URLLoader = new URLLoader();
    var textReq:URLRequest = new URLRequest(“synopsis.txt”);

    textLoader.load(textReq);
    textLoader.addEventListener(Event.COMPLETE, textLoadComplete);

    Just FYI:
    my dynamic text field is called: synopsisBox
    my text document is called: synopsis.txt
    and the little piece at the beginning of the text file is syntext (ie, syntext=start text file content now.)

    Any help is appreciated!

  12. Sara it looks like you’re text file is setting the variable value syntext?

    This is not needed as you are loading the content of the file right into the text field and not via a variable. Also be sure the path to the text file is correct, maybe just try this in the function to see what data you are actually getting on the load

    function textLoadComplete(event:Event):void
    {
    trace(textLoader.data);
    }

  13. Mr Witham:

    I’m using your code to attempt to load a large text file into a dynamic text box w/ scrollbar. It is successfully loading the data, however the scrollbar component no longer works (displays as disabled) and when you click on the textbox or move your mouse wheel, the data that was loaded is cleared from the box.

    What am I doing wrong?

    Thanks for your help!

    GX

  14. ah hah.. nevermind. Deleted the dynamic text box after getting frustrated and created a new one… problem solved!

    Nice code 🙂

  15. I got this code to work but I noticed that it must be in the root of the flash document (first frame) in order to work.

    I initially placed it in the first frame of a movieclip, but it didn’t start, which was a shame since I wanted to have the code for this in the same movieclip as the text field it utilizes.

    Is there some obvious way to do this that I am overlooking?

    Thanks.

  16. Hi Michael,

    It will work, I have created a file with an example using a text field inside a movieclip, you can download it here.

    What I did is,

    I have a movieclip and inside there I have the textArea component with an instance name of myTextField, I also have the code inside the movieclip which looks like this

    — Code begins
    function textLoadComplete(event:Event):void
    {
    myTextField.htmlText = textLoader.data;
    }
    var textLoader:URLLoader = new URLLoader();
    var textReq:URLRequest = new URLRequest(“text.txt”);

    textLoader.load(textReq);
    textLoader.addEventListener(Event.COMPLETE, textLoadComplete);

    // Stop here otherwise it will go back to frame one and start over again.
    stop();
    — Code ends

    Note that I put a stop(); in there to prevent the movieclip from looping over and over.

    Let me know if this solves the problem for you,
    Peter.

  17. Thanks for this! Do you know what I can do if I want to have two dynamic text fields with separate files loading to them on the same page (frame)?

  18. Sure,

    You can just have two instances with different names and point them to the right instance. For example,

    function textLoadAComplete(event:Event):void
    {
    trace(textLoaderA.data);
    }
    var textLoaderA:URLLoader = new URLLoader();
    var textReqA:URLRequest = new URLRequest(”path_to_file”);
    textLoaderA.load(textReq);
    textLoaderA.addEventListener(Event.COMPLETE, textLoadAComplete);

    function textLoadBComplete(event:Event):void
    {
    trace(textLoaderB.data);
    }
    var textLoaderB:URLLoader = new URLLoader();
    var textReqB:URLRequest = new URLRequest(”path_to_file_2”);
    textLoaderB.load(textReq);
    textLoaderB.addEventListener(Event.COMPLETE, textLoadBComplete);

    There is a better way to do this with less code, but this would get you up and running. Anytime I expect to do the same thing more than once I look to make a class that I can just create an instance off to do it with.

    Regards,
    Peter

  19. Awesome responses! I am having a problem with multiple frames though. What if you wanted to have the text to display only on one of the frames in your scene? For me the external text doesn’t go away once you goto a different frame. And sometimes it even hangs around for different scenes. Is there maybe something that refreshes/reloads the as?

  20. Hi Jesse,

    Well there are many ways you could handle the situation you describe. One that comes to mind is putting this code in a class and using it as a value object. Then when you want to remove or add the text to the field again you can either set the text to an empty string or just call back the data from the object.

    Give me a little time and I’ll play around with it some and post back my results.

    Peter.

  21. Thank you for responding so quickly! Let me give you some of my AS so you could take a look at what exactly I am trying to do. I am creating a website entirely in flash. Each of the scenes is a different page to the site. Then inside a scene, frames break down to different sections within the page. Some of those pages need to have the content changed frequently in different areas, which is why I am creating external text files to be loaded.

    Here is my AS for one of the external text files on the About Us page (scene):

    var externalAboutUs1_txt:TextField = new TextField();
    var externalAboutUs1Req:URLRequest = new URLRequest(“aboutUs_content_1.txt”);
    var externalAboutUs1Load:URLLoader = new URLLoader();

    externalAboutUs1Load.load(externalAboutUs1Req)

    externalAboutUs1Load.addEventListener(Event.COMPLETE, textReadyAboutUs1);

    externalAboutUs1_txt.x = 325;
    externalAboutUs1_txt.y = 147;
    externalAboutUs1_txt.border = false;
    externalAboutUs1_txt.width = 250;
    externalAboutUs1_txt.height = 330;
    externalAboutUs1_txt.wordWrap = true;

    var formatAboutUs1:TextFormat = new TextFormat();

    formatAboutUs1.letterSpacing = 1;
    formatAboutUs1.size = 13;
    formatAboutUs1.font = “Abadi MT Condensed Light”;

    externalAboutUs1_txt.defaultTextFormat = formatAboutUs1;

    addChild(externalAboutUs1_txt);
    externalAboutUs1_txt.name = “aboutUsMain1”;

    function textReadyAboutUs1(event:Event):void
    {
    externalAboutUs1_txt.text = event.target.data;
    }

    What’s happening is that the text doesn’t go away when you go to a different scene. It overlaps the other page’s external text. This happens for all external text in all the scenes. Even when you click on the page you are already on, the text overlays on top of the same text…making is darker/bolder.

    I appreciate any advice or help you can give me, THANK YOU!!

  22. At initial glance I noticed that you assign the name ‘aboutUsMain1’ to ‘externalAboutUs1_txt’ when adding it to the stage but you assign the data to ‘externalAboutUs1_txt’ still. Not sure that it would be a problem but you may want to consider creating the instance of the text field during the function after the data is loaded just to keep things nicely organized, and it would prevent any problems with instances that are not used should the data not load for some reason.

  23. I’m not quite sure why I put that line there to begin with. Does it even need to be there? When I delete it nothing changes. And when I delete the instance on the stage the text still appears.

  24. I will try to recreate the situation in a Flash file and make a new post with a link to it from this thread for you if I find a suitable solution to the problem. Might take me a couple of days to find time, but will not forget ya!

  25. I have created a new post on my hosted blog with sample files to a possible solution for using multiple scenes and a OOP based approach to loading and accessing the data, you can find it at this link http://www.uibuzz.com/?p=473 along with a walk through to accompany the code samples.

    This is just one way to approach the problem, I am sure there are many more but I wanted to get a response back to you fast as I’m guessing you need to solve it quickly 🙂

    Hope it helps,
    Peter.

  26. Hi Everybody
    Thanks for the scripting. I hv tried this its working properly , but i am facing one more problem i.e, text alignment. HTMLText is not aliened when i load it on flash file even it font color is not changing as according to CSS file. Can anyone tell me how can i comeout with tihs problem

  27. Hi peter, this post is a great resource for someone like me.

    I’m, however, having the same problem Nisha was having, and you said to apply CSS to text after it’s loaded. How do I go about doing this?

    Here is my code, abridged from all the great comments here:

    var cssUrl:URLRequest = new URLRequest(“announce/css.css”);
    var cssLoader:URLLoader = new URLLoader();
    cssLoader.load(cssUrl);
    cssLoader.addEventListener(Event.COMPLETE,cssLoaded);

    function cssLoaded(event:Event):void {
    var css:StyleSheet = new StyleSheet();
    css.parseCSS(URLLoader(event.target).data);
    announce_txt.styleSheet = css;
    }
    var textUrl:URLRequest = new URLRequest(“announce/announce.html”);
    var textLoader:URLLoader = new URLLoader();
    textLoader.load(textUrl);
    textLoader.addEventListener(Event.COMPLETE,fileLoaded);

    function fileLoaded(event:Event):void {
    announce_txt.htmlText= event.target.data;
    announce_txt.background = false;
    announce_txt.wordWrap = true;
    announce_txt.htmlText = textLoader.data.split(“\r\n”).join(“\n”);
    textLoader.removeEventListener(Event.COMPLETE, fileLoaded);

    }

  28. Hi,

    I think you need to look at the order things are taking place, you have the CSS loading and being attached to announce_txt in the cssLoaded function. This could well happen before the text is loaded due to the asynchronous nature of ActionScript, I would suggest moving announce_txt.styleSheet = css; into the text loaded function and maybe even load the css style sheet after the data has been loaded by moving

    var cssUrl:URLRequest = new URLRequest(“announce/css.css”);
    var cssLoader:URLLoader = new URLLoader();
    cssLoader.load(cssUrl);
    cssLoader.addEventListener(Event.COMPLETE,cssLoaded);

    into a function called in the fileLoaded event. Make sense?

    Let me know if it still gives you a problem.

    Regards,
    Peter.

  29. Thanks Peter for getting back to me,

    I’m still quite a beginner at flash, but from what you said, I moved the above css loading code into the fileLoaded function like so:

    var textUrl:URLRequest = new URLRequest(“announce/announce.html”);
    var textLoader:URLLoader = new URLLoader();
    textLoader.load(textUrl);
    textLoader.addEventListener(Event.COMPLETE,fileLoaded);

    function fileLoaded(event:Event):void {
    announce_txt.htmlText= event.target.data;
    announce_txt.background = false;
    announce_txt.wordWrap = true;
    announce_txt.htmlText = textLoader.data.split(“\r\n”).join(“\n”);
    textLoader.removeEventListener(Event.COMPLETE, fileLoaded);

    var cssUrl:URLRequest = new URLRequest(“announce/css.css”);
    var cssLoader:URLLoader = new URLLoader();
    cssLoader.load(cssUrl);
    cssLoader.addEventListener(Event.COMPLETE,cssLoaded);
    }

    function cssLoaded(event:Event):void {
    var css:StyleSheet = new StyleSheet();
    css.parseCSS(URLLoader(event.target).data);
    announce_txt.styleSheet = css;
    }

    Sadly, it still doesn’t work, and I don’t understand where I was wrong. Another problem I am having is that HTML tags in the html document like is working, but not tags like . Embedding youtube videos and such doesn’t work either. Is there a workaround?

    Thank you!

  30. (woops, the tags disappeared)

    …tags in the HTML document like “b” is working, but not tags like “h1”. Embedding youtube videos and such doesn’t work either. Is there a workaround?

    Thank you!

  31. When you say it doesn’t work I am assuming you mean it is not displaying the CSS styles? I’m curious why you have

    textLoader.removeEventListener(Event.COMPLETE, fileLoaded);

    I have never really seen a need to remove these kind of event listeners for memory or performance improvement.

  32. That’s right, it’s still not displaying the css styles. I have a div.center {text-align:center} in the CSS and a div tag with a class of center in the HTML.

    I’ve also removed the removeEventListener because, like you said, it wasn’t doing anything.

    Do you have any other ideas on whats causing the problem?

  33. Have you tried using the CSS inside the Flash file rather than external to check that it works right? Might want to consider creating the style inside the action script to be sure Flash supports all the tags.

Leave a comment