Loading JavaScript file(s) using HTTPService/URLLoader

In my last post, I talked about JavaScript Flex 2 component that can inject Javascript code in HTML wrapper’s context. I experimented to see, if we can load Javascript files (.js) using HTTPService (or flash.net.URLLoader) in Flex2/AS3 projects and inject it.

Example Flex 2.0 code:

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns="com.abdulqabiz.utils.*"  width="100%" height="100%" creationComplete="onAppInit ()">
import flash.external.ExternalInterface;
import mx.events.*;
import mx.rpc.events.*;
import mx.rpc.http.HTTPService;
import com.abdulqabiz.utils.JavaScript;
private var javascript:JavaScript;
private var service:HTTPService;
private function onAppInit ():void
service = new HTTPService ();
service.url = "test.js";
service.useProxy = false;
service.resultFormat = "text";
service.addEventListener ("result", injectJavaScript);
service.send ();
private function injectJavaScript (event:ResultEvent):void
javascript = new JavaScript ();
javascript.source = String(event.result);
trace ("javascript injected: " + event.result);
private function invokeSayHelloWorld ():void
ExternalInterface.call ("sayHelloWorld");
private function invokeSaySomething (str:String):void
ExternalInterface.call ("saySomething", str);
<mx:Button label="invoke javascript saySomething () function" click="invokeSaySomething ('Hey, how are you?')"/>
<mx:Button label="invoke javascript sayHelloWorld () function" click="invokeSayHelloWorld ()"/>

Test.js used in example:

var myName = "Abdul Qabiz";
function saySomething (str)
alert (str);
function sayHelloWorld ()
alert ("Hello World!");

You would need JavaScript.as (with proper package directory structure) and test.js (code posted above) in place to make above example to work.
I am thinking to load FABridge using this approach. I know, it’s practically of no use except keeping code and logic at one place.

  • bijay narayan das

    I want to load java script.Please help me.

  • Awesome!
    This article was really helpful!
    Thank you.

  • Jeff Werner

    the application I am working was built using your javascript.as component to help render text fields above the flex app to provide a hack on supporting Arabic text. This implementation worked fine, but would break every so often with new flash players or browser releases.
    We just finished our upgrade to flex3 and blaze DS and noticed the Arabic text is no longer working correctly. Have you seen any issues with Flex 3 and your component? mainly the issue is the textArea we are pushing to the wrapper is not fully rendered and is not enabled . However is you type in the area in Arabic mode the text is captured and visible when you switch back to English mode.

  • Krihsna

    I have followed the procedure given by you. It works with firefox 3.0 and doesn’t work with IE6. Please suggest me something solution for this. I will be eagerly waiting for your response.
    Thanking you in advance