$ not defined - javascript错误,试图优化文件

HI guys, my application uses a lot of different javascript files. SO I tried to be quick about it and accomodate all the files in one single file. This I did by creating a single php with the following code:

<?php
header('Content-type: text/javascript');


$js = array( ....   ); // all files to include

$js = array_unique($js);

foreach($js as $oneJs)
    require_once('scripts/'.$oneJs);

And including a reference to this file where I need to include the javascript as:

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

I'm using prototype js here and the scriptaculous libraries - the problem is that I'm getting loads of errors and now half my javascritp wont run. Especially now I'm getting the $ is not defined error. I've included prototype in the list but I'm still getting this error - help please!!!

You need to be careful of two things when doing this.

  1. Make sure the loading order is correct. If you have script files that use jQuery, jQuery needs to be loaded first. The $ is not defined error sounds like jQuery is loaded too late.

    What I sometimes do for this is add numbers to the names (1_jquery.js, 2_dialog.js....) and then do a sort() on the array.

    You could also consider using an array to specify the order of the most important javascript includes, and load the rest in arbitrary order.

  2. Make sure there are no "misunderstood" statements because of missing ";"s at the end of each script file that become glued together. It's a good practice to echo a standalone ";" in between each included file.

The reason is probably the order in which you load the scripts. Make sure to grab them so that all the dependencies are ready when it executes.