Reciprocal JavaScript
Have you ever needed to load a JavaScript based upon some JavaScript condition that was set to true, or some function that was run, or object that was called? (You get the idea)
Well, in some cases, you may just need to do just that. The primary focal point in doing this lies within JavaScript's createElement method. We can use this method to create a new script element to call another file from within the page.
First, lets create a variable named efile then we can assign this the value of that new script element.
var efile = document.createElement("script");
efile.src = "/path/to/myscript.js";
efile.type = "text/javascript";
The above JavaScript code is equivalent to this in HTML:
<script src="/path/to/myscript.js" type="text/javascript"></script>
Next, we tell JavaScript to find the head section of the page, and append a new element into it, namely the previously mentioned variable called efile.
document.getElementsByTagName("head")[0].appendChild(efile);
And thats it. But of course, this is not in itself really all that useful.
But, if we put the above logic into a function (say, "loadScript" for example) then we can call multiple scripts at once!
function loadScript(url) {
var efile = document.createElement("script");
efile.src = url;
efile.type="text/javascript";
document.getElementsByTagName("head")[0].appendChild(efile);
}
onload = function() {
loadScript("js/pngfix.js");
loadScript("js/test.js");
}
We can fire the reciprocal scripts onload or based upon any other conditions that might be set. Happy coding. 
Apr 05, 2008
Comments
This article hasn't been commented yet.

Write a comment
* = required field