Skip to content

Instantly share code, notes, and snippets.

@MrScruffy04
Last active April 22, 2016 04:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MrScruffy04/6908211 to your computer and use it in GitHub Desktop.
Save MrScruffy04/6908211 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>
*/
@MrScruffy04
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment