View Full Version : Include a javascript file in another javascript

05-25-2005, 01: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?

05-25-2005, 02: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>

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

05-25-2005, 04: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, 05: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.

05-26-2005, 06:26 AM
function includeJS(jsPath){
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", jsPath);

05-27-2005, 12:25 AM
What does the above code do and how do I use it?

05-27-2005, 04: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.