This is a mirror of official site: http://jasper-net.blogspot.com/

Combine and compress javascript and css files in ASP.Net MVC

| Thursday, December 2, 2010
Goal:
When loading js or css files, combine all the js files into one and all css files into one file respectively when rendering to improve on performance. Also compress if need be on the fly.

In this example we use many css files and even more js files to organize the ASP.Net Mvc web app into manageable pieces. The reason for the separation is mainly because it gives the team the ability to work on different part of the web app by working on the affected css or js files. It also helps to decide at a very granular level which css or js files to load and cache in the browser and which ones are very unique and/or specific and/or large so as to load only when really needed. For example I have an extremely large contract page with about 4000 lines of jQuery to handle a spreadsheet like functionality. It is not used often and used only by certain sales reps. Do not want to load this file as part of the generic/global js file since it would be wasted space for most part. This file is loaded on the fly when needed. How that is done is another story :-) Since my app is a CRM app, it has many screens that have unique css styling requirements and so in some situations the css file should only be loaded when needed. The reasons are really not that important in the context of this blog, just want to show you how to do this in ASP.Net Mvc if and when the need arises.

System Requirements:
.Net 2+

ASP.Net Mvc v1+

Solution:

In your Master file head section
<link rel="stylesheet" type="text/css" href="<%=Url.RouteUrl(new {controller = "Scripts", Action = "GetAllCss"})%>" />
<script type="text/javascript" src="<%=Url.RouteUrl(new {controller = "Scripts", Action = "GetAllScripts"})%>"></script>

In the Mvc ScriptController controller:
       public static IPathMapper ServerPathMapper { get; set; }

       protected static bool Enable;
       protected static bool EnableHtmlCompression;
       protected static bool EnableHtmlMinification;
       protected static bool EnableProfiler;
       protected static bool EnableScriptCompression;
       protected static bool EnableScriptMinification;


Read more: Renso Hollhumer

Posted via email from .NET Info

0 comments: