Question: I'm working on my first very complex JQuery based application.

A single web page can contain hundreds of JQuery related code for example to JQueryUI dialogs.

Now I want to organize code in separated files.

For example I'm moving all initialization dialogs code `$("#dialog-xxx").dialog({...})` in separated files and due to reuse I wrap them on single function call like

**dialogs.js**

```
function initDialog_1() {
  $("#dialog-1").dialog({});
}

function initDialog_2() {
  $("#dialog-2").dialog({});
}

```

This simplifies function code and make caller page clear

```
$(function() {
  // do some init stuff
  initDialog_1();
  initTooltip_2();
});

```

Is this the correct pattern?

Are you using more efficient techniques?

I know that splitting code in many js files introduces an ugly band-bandwidth usage so.

Does exist some good practice or tool to 'join' files for production environments?

I imagine some tool that does more work than simply minimize and/or compress JS code.

Answer: 
I'm working on something fairly complex in JS right now, and have been wondering the same thing. I looked at various "module" implementations but while they look "cool" they don't seem to offer much value.

My plan at this point is to continue referencing lots of script files from my .html page (the plan is to only have one .html page, or very few).

Then when I'm building the release version, I'll write a very simple tool to fit into my build process, which will discover all the scripts I reference from the .html pages and concatenate them into one file, and replace the multiple `<script>` elements with a single one, so that only one request is necessary in the "release" version.

This will allow the compression to work across all the script text instead of on each separate file (like doing `tar` followed by `gzip`) and should make a difference to the script download time (though I should stress I haven't actually implemented it yet).
You usually want to keep all of your javascript inside one file. Less HTTP requests is usually better. If you take a look at the jQuery source, you'll notice that every function and property is right there in the jQuery global object:

```
jQuery.fn = jQuery.prototype = {
    init: function(){ ... },
    animate: function() { ... },
    each: function() { ... },
    // etc
}

```

However, the pattern you seem to be interested seems similar to the "module" pattern. The YUI framework uses this pattern, and allows developers to "require" different components of the library from the core module via HTTP request. You can read more about YUI here:

<http://developer.yahoo.com/yui/3/yui/>