A popular approach is to use a strategy like this. The gist of this approach is to organize your page initializers in an object literal by controller name and action, something like
Every initializer is included in the application bundle, bloating its file size
The page queries the registered initializers to see if it has work to do. I’d rather the initializer script told the page it has work to do when the document is ready.
An approach that has worked for me looks something like this:
I like this approach for a few reasons:
Only one initializer is included on a page.
It provides a convention for where page initializers will be located on the server.
The size of the compiled application.js file is reduced because the page initializers aren’t included in the bundle.
The initializer tells the page it has work to do.
There is an extra request to the server for the page initializer file.
A convenient place for storing data that you might need to generate while rendering the current action. Better to place that data here than on window where another object with the same name might be overwritten
A convenience method for registering document ready handlers. When the document ready event fires, the intializer is executed with the page initializer as the first argument. This structure should make it easy to unit test your initialization scripts.
This is obviously just one of many approaches out there. What other approaches have worked for you?