Easily Manage Many Javascript/CSS Files in Your .Net MVC Project

I’ve worked on a few projects where we crammed all of our javascript into one file. This made navigation of the file a sheer nightmare. Now, I use the SmallSharpTools.com Packer to cram all of my JS files into a single minified JS file. One of the last MVC project I worked on had 143 javascript files that were minified into a single one. There is one frustrating thing about this. You must build your project every time you change javascript code. You can also retrofit these methods for CSS files.

You can solve this by throwing an if statement around your JS includes like this:


<% if (!Model.IsDev) {  %>
	
<%} else {%>
	
	
	
	
	
<%} %>

This isn’t too bad, but it can still be kinda messy if you are working on a large project. If you structure you directories to mimic your Views like I do (see image below) it becomes really tedious to manage every file and remember to add new js files to your includes.

I wrote a simple HTML Helper that will help change this:












Into This:


<%= Html.IncludeJSDirectory("/Scripts2/AllYour/")%>
<%= Html.IncludeJSDirectory("/Scripts2/BaseAre/")%>
<%= Html.IncludeJSDirectory("/Scripts2/BelongToUs/")%>

Here is the code for the HTML Helper:


using System.IO;
using System.Text;

namespace System.Web.Mvc {
	public static class IncludeHelper {

		public static string IncludeJSDirectory(this HtmlHelper helper, string directory) {
			DirectoryInfo dir = new DirectoryInfo(HttpContext.Current.Server.MapPath(directory));

			if (!dir.Exists) 
				return string.Empty;

			StringBuilder sb = new StringBuilder();

			string href = string.Empty;
			foreach (var i in dir.GetFiles("*.js")) {
				href = string.Format("{0}{1}", directory, i.Name);

				TagBuilder _script = new TagBuilder("script");
				_script.MergeAttribute("type", "text/javascript");
				_script.MergeAttribute("src", href);

				sb.Append(_script);
			}

			return sb.ToString();
		}
	}
}

Currently, this doesn’t support URLs leading with a tilde. I have a code snippet to handle it, but I didn’t write it. I’ve been working with this solution for a couple of weeks and it works great on my local machine. It has made working with many Javascript files very easy. I would strongly recommend not using this for a production environment and to look into SmallSharpTools.com Packer to minify your javascript and css files.

I’m a Technology Architect for Rockfish Digital. I’ve been there since 2007. I love coding and spend most of my time in C# and JavaScript. I’m a firm believer in the Full Stack Developer.

Author: worthyd

I'm a Technology Architect for Rockfish Digital. I've been there since 2007. I love coding and spend most of my time in C# and JavaScript. I'm a firm believer in the Full Stack Developer.

Leave a Reply

Your email address will not be published. Required fields are marked *