views:

44

answers:

2

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!!!

A: 

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.

galambalazs
+2  A: 

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.

Pekka
$ is also is prototype but in this case I am including prototype as the first script in the stack. WHat else should I look out for?
Ali
@Ali what line are you getting the error in?
Pekka
From firebug - there aren't any errors being called upon page load - however I get the error whenever an event is executed which makes use of the $ function
Ali
@Ali then you will need to show the JS file. Maybe paste it on pastebin.com or jsbin.
Pekka
@Ali you could also try running it through JSLint.com.
Pekka
Ok I got it figured out - actually one of the files which I was including I had tried to compress it using a third party minifyer but the error was in that file. Since it was all being imported into one single js.php file the whole file was rendered disfunct on account of that. Thanks again for the help got it sorted out!
Ali
COuld you recommend a good javascript compressor thats reliable? I used a web based compressor here...
Ali
@Ali I have no big experience with compressors. I usually glue them together and let Apache handle the compression.
Pekka