I wanted to get your opinion about managing scripts in ASP .NET MVC. There are 2 problems I am particularly curious about:
- Tracking script include dependencies of views
- Managing and minifying view scripts
Just like in many projects my views are composed of several partial views and editor templates. I like to keep the scripting relating to these views in the same code entity e.g.
SigningKeysForm partial view should have its own JQuery/JQueryUI scripts.
Which means any view which renders this partial view should include JQuery/JQueryUI script files.
Also another issue is when a view is composed of several such partial views, it means the javascipt in the partial views will be in several locations in the generated html.
My current approach to these problems is exploiting the top down parsing of views in ASP .Net MVC.
For tackling first problem I define a HtmlHelper extension to include a script e.g.
<% Html.RequireScript(Scripts.JQuery); %>
This way in each partial view and view I explicitly call out which scripts are required. The implementation of this method is to create a HashSet on current HttpContext and add the required script there.
In my master page I have another HtmlHelper extension which checks the HttpContext and renders the script include tags e.g:
<%=Html.RenderScriptIncludeTags()%>
This way I can track the requirements of views and render only the required script includes.
For the view scripts I am employing a similar approach. I use a custom Asp .Net user control which instead of rendering its content stores the script content into a buffer on HttpContext e.g:
<mvc:script runat="server">
$(function(){
alert("Hello " + "<%=Model.Name%>");
});
</mvc:script>
Again in the Master view I have a HtmlHelper extension which minifies (if needed) the stored scripts and renders them e.g:
<%=Html.RenderScripts()%>
</body>
I think this works as a solution, but it requires the script includes and scripts to be in the bottom of the master page. This means the script includes are not in the head section.
I want to know if there are better ways to manage the script requirements and in view page scripts with ASP .NET MVC.