1

When you are loading JavaScript files via the <script> tag, you can only do it one-by-one, ie <script src="myFile.js"> or so I'm assuming. Is there a way to load an entire directory of .js files like src="dir/*"?

1 Answer 1

5

No - you cannot, by definition, (see RFC 1738) incorporate a wildcard into a URL.

If you have server-side scripting access you could embed a block of code which inserts a script tag for every file read from a directory or you could concatenate the scripts on-the-fly (concatenation is generally preferable as it requires less overhead to download a single concatenated file).

Most efficient solution: concatenate the relevant script files and link to that file from one <script> declaration.


[H]ow exactly would I do that on-the-fly?

Here's an example of how you might do that with a PHP file named all-js.php in the same directory with all your scripts:

<?php
    $output = '';
    $dir = dirname(__FILE__);
    $files = scandir( $dir );
    if ( $files )
    {
        foreach ( $files as $file )
        {
            if ( '.js' == substr( $file, -3, 3 ) )
                $output .= "/* file: $file */\n\n" . file_get_contents($file) . "\n\n";
        }
    }
    echo $output;
?>
3
  • mmm.. I know what "concatenate" means, but how exactly would I do that on-the-fly?
    – Snailer
    Commented Apr 2, 2011 at 22:46
  • (Added PHP example)
    – danlefree
    Commented Apr 3, 2011 at 1:37
  • Wow thanks for the help! I'm just getting into php now, so I only know the basics. It works great!
    – Snailer
    Commented Apr 4, 2011 at 3:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.