I\'m trying to cobble together a php style include function for javascript. The route I\'m taking is through a XMLHttpRequest. The included file will load, but the functions
OrbMan pointed me in the right direction on this one, but the solution to this particular method of including Javascript files requires the functions be defined differently; like this
window.myFunction = function(){
alert("Hey There!")
}
A potential upside to this is that any functions in the included file that are declared the normal way are encapsulated so they are only available to the window.functions from that file... as far as I can tell.
It's simple enough to use the DOM to add the required script:
function include(jsFile)
{
var sEl = document.createElement("script");
sEl.type = "text/javascript";
sEl.src = jsFile;
document.getElementsByTagName("head").appendChild(sEl);
}
Browsers will even download this file asynchronously, and script elements have an onload
event that works in most (all?) popular browsers so you can also add a callback function if you like. The obvious downside is that functions wouldn't become available to the current script until the file is downloaded and parsed.
Instead of loading the JavaScript file via AJAX, why not create a <script>
tag and insert that into the page? That will allow the JavaScript to be parsed in the global scope. Take a look at how Scriptaculous' require
function works
Change the way you declare your functions and it should solve the scoping issue. Instead of:
function add(a, b)
{
return a + b;
}
do this:
var add = function(a, b)
{
return a + b;
}