Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 359
Hristo Avatar asked Nov 13 '10 22:11

Hristo


People also ask

How do you include a JavaScript file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

Should I put all my JavaScript in one file?

To avoid multiple server requests, group your JavaScript files into one. Whatever you use for performance, try to minify JavaScript to improve the load time of the web page. If you are using single page application, then group all the scripts in a single file.

Where do I put JavaScript script files?

JavaScript in <head> or <body> You can place any number of scripts in an HTML document. Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.


1 Answers

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.

like image 191
Mark Bessey Avatar answered Sep 18 '22 09:09

Mark Bessey