...

View Full Version : Include a javascript file in another javascript



MyttO
05-25-2005, 12:55 PM
I have a Javascript library composed of a dozen of .js files.
I want to prevent the HTML file from being polluted with many html <script> elements, one for each of the inclusions.

Is there a way for a javascript to include an external javascript file?

jbot
05-25-2005, 01:39 PM
Is there a way for a javascript to include an external javascript file?

just stick to HTML. :rolleyes:


<script src="myjsfile.js"></script>

mrruben5
05-25-2005, 03:13 PM
Yes. Do it with document.write.

rlemon
05-25-2005, 03:19 PM
call one Js file and using php, or some other SS lang to include all the other js files into that?

Eternity Angel
05-25-2005, 04:44 PM
Straight-forward answer:


Include one JS file that will contain all the other scripts:


<script type="text/javascript" src="thejsfile.js"></script>

And in thejsfile.js:



document.write('<script type="text/javascript" src="file1.js"></script>');
document.write('<script type="text/javascript" src="file2.js"></script>');
document.write('<script type="text/javascript" src="file3.js"></script>');
document.write('<script type="text/javascript" src="file4.js"></script>');
document.write('<script type="text/javascript" src="file5.js"></script>');

... etc.

glenngv
05-26-2005, 05:26 AM
function includeJS(jsPath){
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", jsPath);
document.getElementsByTagName("head")[0].appendChild(script);
}

ebay258
05-26-2005, 11:25 PM
What does the above code do and how do I use it?

glenngv
05-27-2005, 03:23 AM
It dynamically adds external scripts through DOM. A more elegant way than using document.write. You just call the includeJS() function passing the path to the external script.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum