I'm aware, one can "import" script files from within javascript like this:
var imported = document.createElement('script');
imported.src = '/path/to/imported/script.js';
document.head.appendChild(imported);
For that the filename (here: script.js
) and its location must be known in advance.
I have a number of optional modules than can be present or not in my main project. Each module is it's own javascript file. I want to detect which one is present in the scripts/
directory and run them in the above fashion, i.e. I don't know the filenames in advance. I know javascript is client-side and has no access to the server-side directory, but maybe there is a workaround with request objects or something like that. I do not have a server-side scripting language available. Is that at all possible?
To illustrate, I have a file /scripts/main.js
that is always present and included from an HTML file index.html
. Then there is a number of other *.js
files in /scripts/
, the modules. I want them to be automatically included by main.js
. To Illustrate:
<!-- In index.html -->
<html><head>
<title>Include Scripts</title>
<script type="text/javascript" src="scripts/main.js">
</head><body>
<!-- ...more stuff... -->
</body></html>
While main.js
might look somthing like this:
// In main.js
scripts = findScripts( 'scripts/*.js' ); // How do I do this?
for( i=0; i<scripts.length; i++ ) {
if( scripts[i].match(/main.js$/ ) continue;
var imported = document.createElement('script');
imported.src = scripts[i];
document.head.appendChild(imported);
}
And then the modules in the script directory should be run on their own.