How can I combine my JavaScript files and still have my callbacks wait for a ready state?

First of all: Depending on how much code you have, you should consider, if serving all your code in one file is really a good idea. It's okay to save http-requests, but if you load a huge chunk of code, from which you use 5% on a single page, you might be better of by keeping those js files separated (especially in mobile environments!). Remember, you can let the browser cache those files. Depending on how frequent your code changes, and how much of the source changes, you might want to separate your code into stable core-functionality and additional .js packages for special purposes. This way you might be better off traffic- and maintainance-wise.

Encapsulating your functions into different objects is a good idea to prevent unnecessary function-hoisting and global namespace pollution.

Finally you can prevent calling needless event handlers by either:

Introducing some kind of pagetype which helps you decide calling only the necessary functions.

or

checking for the existence of certain elements like this if( $("specialelement").length > 0 ){ callhandlers}

to speed up your JS, you could use the Google Closure Compiler. It minifies and optimizes your code.


I think that all you need is a namespace for you application. A namespace is a simple JSON object that could look like this:

var myApp = {
    homepage : {
      showHeader : function(){},
      hideHeader : function(){},
      animationDelay : 3400,
      start : function(){} // the function that start the entire homepage logic
    },
    about : {
    .... 
    }
}

You can split it in more files:

  1. MyApp will contain the myApp = { } object, maybe with some useful utilities like object.create or what have you.
  2. Homepage.js will contain myApp.homepage = { ... } with all the methods of your homepage page.
  3. The list goes on and on with the rest of the pages.

Think of it as packages. You don't need to use $ as the main object.

 <script src="myapp.js"></script>
 <script src="homepage.js"></script>
 <-....->
 <script>
   myApp.homepage.start();
 </script>

Would be the way I would use the homepage object.

When compressing with YUI, you should have:

<script src="scripts.min.js"></script>
<script>
    myApp.homepage.start();
 </script>