Quantcast
Channel: Williamo's Blog » Software Development
Viewing all articles
Browse latest Browse all 15

Quick Update: CSS/JS Auto-Minification in ASP.NET

$
0
0

I’ve been trying for weeks to write up a good technical article about a recent CSS/JavaScript minification handler for ASP.NET (ASHX/HttpHandler) that I whipped up, but our current release has been so busy, I haven’t had enough time to really put it all together.

Just wanted to post a quick update for everyone who mentioned they’d like to hear about it that I’ll be posting more info as soon as I can. =)

In the meantime, here are links to some of the articles that helped me construct the custom handler in the first place:

And, my own pride and joy (this damn code took me forever, only because I had to do all sorts of research and testing with Regex in C#), the function that will fix relative paths in the combined CSS files by replacing them with absolute paths based on your application root:

/// <summary>
/// CSS Only: Replaces relative paths in url(...) properties within the specified script.
/// </summary>
/// <param name="scriptBody">The pre-combined script, passed from CombineScripts().</param>
/// <param name="scriptPath">The relative path where scripts are located (ex: ~/CSS/).</param>
/// <param name="applicationPath">The absolute application path. (ex: /ApplicationRoot).</param>
/// <returns></returns>
private static String FixRelativePaths(String scriptBody, String scriptPath, String applicationPath)
{
 scriptPath = VirtualPathUtility.AppendTrailingSlash(scriptPath);
 String relativeRoot = VirtualPathUtility.Combine(applicationPath, scriptPath);

 Regex cssUrlReference = new Regex("(?<=url\\()(.+?)(?=\\))", RegexOptions.Singleline);
 Regex invalidPathChars = new Regex("[ '\"]+", RegexOptions.Singleline);

 MatchCollection urlMatches = cssUrlReference.Matches(scriptBody);
 foreach (Match m in urlMatches)
 {
 String oldPath = Regex.Replace(m.Value, "[ '\"]+", "");
 String newPath = VirtualPathUtility.Combine(relativeRoot, oldPath);
 newPath = VirtualPathUtility.ToAbsolute(newPath);
 scriptBody = scriptBody.Replace(m.Value, newPath);
 }

 return scriptBody;
}

I’d love to read your comments and/or questions about this code, so please feel free to post your thoughts in the comments on this post.

I’ll try to get you the full meal deal on this code as soon as I can. =)


Filed under: ASP.NET, jQuery, Software Development, Web Development Tagged: ashx, asp.net, c#, combine, compress, css, httphandler, javascript, minify, Programming, Software Development, webdev

Viewing all articles
Browse latest Browse all 15

Trending Articles