...

View Full Version : Importing JavaScript files within a function



bauhsoj
09-23-2005, 03:56 PM
Is it possible to import JavaScript files dynamically from within a JavaScript function?

I know this can be done in HTML using <script src="something.js"></script>.

I need to dynamically have access to a function in a file but only when a certain JS method in a certain class needs it. I don't want to have to include it everytime in the HTML code when it is used to rarely (mainly for debugging).

KC-Luck
09-23-2005, 03:59 PM
there are several ways to add a script dynamically, but you must keep in mind that you will not get "instant" access to it. it needs to be loaded into memory of the browser and properly parsed by script engine, before made available, and this type of "late-binding" could interupt your variables, blah...

you can also, append a script and add event listener to let you know when that particular script is loaded to the page. (a prefered method)

TNO
09-23-2005, 04:04 PM
This is a pretty ugly idea, but it may work:

create an IFRAME element on your page like this:


<IFRAME ID="Script" NAME="Script" src="about:blank" style="display:none"></IFRAME>

now, when you have your function and you want to access an outside .js dynamically, do this:

function getJS(){
document.all.Script.src="MyCode.js";
document.all.Script.Function/Var/Object/etc. = Bleh;
}

Like I said, Not a pretty idea, and there are most likely better ones, but I know this works. (unless its a separate domain).

Agekay
09-23-2005, 07:18 PM
Use this:

/// <summary>
/// imports a script into the document
/// <summary>
/// <remarks>
/// script reference is appended to the calling script tag
/// <remarks>
function Import(scriptLocation)
{
document.write('<script type="text/javascript" src="' + scriptLocation + '"><\/script>');
}


This works, because the <script> tag is appended to the calling script tag. So that the browser can parse it after it finished parsing the calling script tag.

bauhsoj
09-29-2005, 09:47 PM
I'll try that and see if I can get it to work.

Thanks for the help!

glenngv
09-30-2005, 12:27 PM
var script = document.createElement("script")
script.setAttribute("type", "text/javascript");
script.setAttribute("src", "path/to/file.js");
document.getElementsByTagName("head")[0].appendChild(script);



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum