I'm trying to determine the best way to structure my application so that I don't get a lot of javascript splattered all over the place.
I have an ASP.NET MVC application with a view which loads a sllooooowwwww partial view using Michael Kennedy's approach to Improve perceived performance of ASP.NET MVC websites with asynchronous partial views. The partial view itself is rendering a DataTables grid (which has its own CSS/JS files), as well as Javascript-based configuration for the grid itself (column formatting, sorting defaults, editor configuration, etc).
My question is what is a clean way to structure and maintain all this? I have at least 3 varieties of scripts (CSS and/or JS) involved here:
- The JS on the main view which loads the partial view.
- The CSS/JSfiles for DataTables
- The JS inside the partial view which runs on
$(document).ready()
and configures that particular grid.
I can control (on the main view) where the CSS/JS are rendered using Razor's @section
for scripts/styles (Item #1 above). However, a partial view can't take advantage of the @section
functionality, so any CSS/JS in a partial view gets injected into the middle of the page. That doesn't really set well with me, because then the rendered HTML looks all nasty with CSS/JS showing up in the middle of the main view. I know things like Cassette can help with Item #2 when the CSS/JS are all stored in external files.
But what about Item #3 where I have CSS/JS which is very specific to that partial view? It may be things as small as attaching click event handlers for the view or configuring JQuery plugins, but does that mean I should separate that out into another JS file? I don't like separating these things if I don't need to, especially the grid configuration for each partial view.
In my case, I have an application with several views containing these partial views which render grids, and none of the grids contain the same set of columns - so the JS configuration for each grid is different which runs on $(document).ready()
.