Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hoangitk/f2f1ce4f966f1046734c043ce168c0c4 to your computer and use it in GitHub Desktop.
Save hoangitk/f2f1ce4f966f1046734c043ce168c0c4 to your computer and use it in GitHub Desktop.
Allows one to minify JS and CSS within a Razor View. See usage at the bottom of the source.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Optimization;
using Microsoft.Ajax.Utilities;
namespace System.Web.Mvc
{
public static class OptimizationExtensions
{
public static MvcHtmlString JsMinify(this HtmlHelper helper, Func<object, object> markup)
{
if (helper == null || markup == null)
{
return MvcHtmlString.Empty;
}
var sourceJs = (markup.DynamicInvoke(helper.ViewContext) ?? String.Empty).ToString();
if (!BundleTable.EnableOptimizations)
{
return new MvcHtmlString(sourceJs);
}
var minifier = new Minifier();
var minifiedJs = minifier.MinifyJavaScript(sourceJs, new CodeSettings
{
EvalTreatment = EvalTreatment.MakeImmediateSafe,
PreserveImportantComments = false
});
return new MvcHtmlString(minifiedJs);
}
public static MvcHtmlString CssMinify(this HtmlHelper helper, Func<object, object> markup)
{
if (helper == null || markup == null)
{
return MvcHtmlString.Empty;
}
var sourceCss = (markup.DynamicInvoke(helper.ViewContext) ?? String.Empty).ToString();
if (!BundleTable.EnableOptimizations)
{
return new MvcHtmlString(sourceCss);
}
var minifier = new Minifier();
var minifiedCss = minifier.MinifyStyleSheet(sourceCss, new CssSettings
{
CommentMode = CssComment.None
});
return new MvcHtmlString(minifiedCss);
}
}
}
/*
<script type="text/javascript">@(Html.JsMinify(@<text>
// JS code here
</text>))</script>
or
<style type="text/css">@(Html.CssMinify(@<text>
/* CSS rules here * /
</text>))</style>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment