Adding Javascript file dynamically using Atlas

The question came up on the Microsoftgadgets forum:

Is there an easy way to include one .js file within another?

Yes there is away to add a javascript file to your page dynamically by using the Web.Network.createRequest method.

function OnScript(script)
{
Web.Utility.Script.attachScript(script, document.body, null);
}
var r = Web.Network.createRequest(Web.Network.Type.Script, jsToAddUrl, null, OnScript);

r.execute();

OnScript is the asynchronous callback that handles the Response of the Request. The arguments for attachScript causes the script to be attached to the document Body. The third argument is a placeholder for a callback method to respond once the script has been attached.

In order to get the script we create a request of type Script, passing the requested js file's url and the callback method to handle the request. The third argument is an open slot for an object used to persist store between requests.

And that's it, once attached the script runs any open JavaScript and the methods are available for use.

posted on Dec 7th, 2005 | Permalink | Comments (3)

3 Comments »

  1. Or you could just document.write() the corresponding <script> tag... I've built a javascript "include" function around this: http://www.hispanicbusiness.com/_client_common/js/include.js

    Comment by Maurits - December 13, 2005 @ 2:01 PM
  2. The advantages that come to mind using this method is first you know if the script is reachable at the requested url and it checks to make sure the script is not already attached, preventing code from running more than once.

    Comment by Adam Kinney - December 15, 2005 @ 12:02 AM
  3. it didnt work with me
    I want to add one js file to another the first contains all common global variables and the other uses it but this method failed when I reference the variable defined in the first one an error is arised saying that the variable is not defined

    Comment by Enas Qawasmi - June 14, 2006 @ 6:14 AM

Leave a comment