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

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


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.


What about using a server-side script to generate the script tag lines? Crudely, something like this (PHP) -

$handle = opendir("scripts/");while (($file = readdir($handle))!== false) {    echo '<script type="text/javascript" src="' . $file . '"></script>';}closedir($handle);


Given that you want a 100% client side solution, in theory you could probably do this:

Via XmlHttpRequest, get the directory listing page for that directory (most web servers return a listing of files if there is no index.html file in the directory).

Parse that file with javascript, pulling out all the .js files. This will of course be sensitive to the format of the directory listing on your web server / web host.

Add the script tags dynamically, with something like this:

function loadScript (dir, file) { var scr = document.createElement("script"); scr.src = dir + file; document.body.appendChild(scr); }