How can I include all JavaScript files in a directory via JavaScript file?

Hristo picture Hristo · Nov 13, 2010 · Viewed 112.6k times · Source

I have a bunch of JavaScript files that I would like to include in the page, but I don't want to have to keep writing

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

So is there a way to include all files in a directory (unknown size)? Can I do something like...

$.getScript("js/*.js");

... to get all the JavaScript files in the "js" directory? How can I do this using jQuery?

Answer

Mark Bessey picture Mark Bessey · Nov 13, 2010

In general, this is probably not a great idea, since your html file should only be loading JS files that they actually make use of. Regardless, this would be trivial to do with any server-side scripting language. Just insert the script tags before serving the pages to the client.

If you want to do it without using server-side scripting, you could drop your JS files into a directory that allows listing the directory contents, and then use XMLHttpRequest to read the contents of the directory, and parse out the file names and load them.

Option #3 is to have a "loader" JS file that uses getScript() to load all of the other files. Put that in a script tag in all of your html files, and then you just need to update the loader file whenever you upload a new script.